Reputation: 1
This has bothered me, I have just gotten back into c++ lately, and am well aware of references. Why does it seem there is no difference between b and c below. In other words, intuitively I would think c not being a ref variable would take a copy. It got me thinking when considering the problem of returning a reference to a local variable.
int a = 10;
int& func()
{
return a;
}
int &b = func();
int c = func(); // shouldn't this make a copy into c but c acts like a reference.
Upvotes: 0
Views: 51
Reputation: 1
Thanks for the answers, makes sense now. This question started from "why can't I return a local variable reference to a variable if its a copy?" Well, I realized because its too late at that point - the stack is gone. I was thinking the copy could be made before the stack went away - wrong! You can return to a reference but when you use it, segfault. Return to a variable and, segfault immediately since it tries to copy.
int& func() // compile warning
{
int a = 10;
return a;
}
int &b = func(); // ok, but segfault if try to use b.
int c = func(); // segfault immediately
Upvotes: 0
Reputation: 1
I would think
c
not being a ref variable would take a copy.
c
is indeed a copy of a
. Note that int c = func();
is copy initialization while int &b = func();
is reference initialization.
This means that if you make changes to c
they will not be reflected on a
. Demo
int a = 10;
int& func()
{
return a;
}
int &b = func(); //reference initialization
int c = func(); //copy initialization
int main()
{
c = 20;
std::cout << a<< " "<< b <<" "<< c <<std::endl; // 10 10 20
return 0;
}
Note also the emphasis on "initialization" instead of "assignment". These terms have different meaning in C++ unlike other languages(python for instance).
Upvotes: 1