tags:

views:

153

answers:

4

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?

+1  A: 

Yes, I prefer the second option as it prevents the copy being created.

Naveen
A: 

You are correct the above copies. The lower does not.

The second one is the preferred one.

Ronny
+15  A: 

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.

Charles Bailey
A: 

(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();
Austin
Returning by reference is fine for member functions, and for some others such as operator<<() where a reference is passed in as a parameter.
anon
Did I not say "You should return by reference only if the function is a method of a class"?
Austin
@Austin Your first sentence: "You should really not return by reference.", which is incorrect.
anon
@Austin And BTW, the downvote wasn't me.
anon