Reputation: 2897
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?
Upvotes: 1
Views: 195
Reputation: 821
(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();
Upvotes: -1
Reputation: 4845
You are correct the above copies. The lower does not.
The second one is the preferred one.
Upvotes: 0
Reputation: 791879
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.
Upvotes: 15
Reputation: 73443
Yes, I prefer the second option as it prevents the copy being created.
Upvotes: 1