passing by reference? safe?

Hi i just have a quick question about the reliability of passing via reference.


One of the fisrt thing I learn when learning C++ is that this is unsafe.
1
2
3
4
5
6
7
8
9
10
11
12
13
14

void myfunction(int* i)
{
    someMassiceFunction();
    cout << *i;
}

int main (int argc, char** argv)
{
    int i = 8;
    myFunction(&i);
    return 0;
}


But am I right in thinking that passing stack data by reference suffers from the same downfalls?
I don't understand what you are posting, and its relationship to what you are asking. In your code (where I might add, your function or its call is mis-spelled), you are declaring a function that takes a pointer to an int as a parameter - not a reference. In main() you are correctly passing to myfunction the address of i. There isn't anything wrong with what you are doing there, its just that you are asking about passing by reference, but showing an example where you are passing by value a pointer.
Passing by pointer is indeed not as safe as passing by reference. In C, however, passing 'by reference' is a non-existent feature. In C++, passing by reference looks (for example) like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

void foo(int& bar) {
  bar = 0;
}

/***/

int main(void)
{
  int magic_number = 69;

  foo(magic_number);
  std::cout << magic_number;

  return 0;
}


This should print out 0. :3
Last edited on
You just need to make sure that the lifetime of the caller outlives the lifetime of the callee.
For example, don't pass something to a different thread by reference if you are not sure that the object will remain valid as long as it's needed.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Thread
{
public:
  void doWorkWith(MyClass& m);
};

void myFunc(Thread* t)
{
  MyClass m;
  t->doWorkWith(m);
  // m get's destroyed here
  // undefined behavior if t still uses it
};

Topic archived. No new replies allowed.