return by reference - which of the two is the correct one
i have the function: const A& f(...) {...}
开发者_运维技巧a. const A a1 = f(..);
b. const A &a2 = f(...);
which of the is the better one to use? in both cases, if i understand correctly, i prevent the possibility of modifying the returned object. in the first option, the copy constructor of A will be called - am i correct?
It depends on what you want.
In the first case you create a new const object that is constructed from the returned reference. It will be a snapshot of what was returned and will be valid for its entire lifetime.
In the second you just initialize a reference. This means that any changes to the original object will be visible through the reference but there is a danger that the referred object will be destroyed while the reference is still alive.
Yes, I prefer the second option as it prevents the copy being created.
You are correct the above copies. The lower does not.
The second one is the preferred one.
(Updated)
You should return by reference if the function is a method of a class and you are returning a reference to one of the members of that class. If you are creating the object in the function and then returning a reference to it, you are returning a reference to an object that doesn't exist anymore--when the stack unwinds, the object created in that function is destroyed.
You could also do it this way:
A someA;
f(someA); // Assuming that f's signature is void f(A&)
Or this way:
auto_ptr<A> someA = f();
精彩评论