views:

139

answers:

4

Consider the following code snippet:

list<someClass>& method();
....
list<someClass> test = method();

What will the behavior of this be? Will this code:

  1. Return a reference to the someClass instance returned by return value optimization from method(), and then perform someClass's copy constructor on the reference?

  2. Avoid calling the copy constructor somehow?

Specifically, I have methods that are returning very large lists, and I want to avoid calling copy constructors on each return value.

EDIT: Erm, sorry, code compiles now...

+3  A: 

The copy constructor will have to be called, because this code must make a copy: the method() function returns a reference to some object, a copy of which must be stored in the variable test.

Since you are returning a reference and not an object, there is no need for return value optimization.

If you do not want to make a copy of the list, you can make test a reference:

list<someClass>& test = method();

However, test will then refer to the original list, so any modifications made to test will also be made to the original list, and whenever the original list is destroyed, test will become invalid (which means you have to be more careful with object lifetimes).

James McNellis
A: 

Well, you can't assign a list to someClass (unless you overloaded the assignment operator or copy constructor, and use the returned list to copy construct). If you didn't this shouldn't compile.

fingerprint211b
There is no assignment going on in the OP's code.
anon
A: 

Looking at your code it is difficult to hazard a guess as to what you are trying to achieve here by returning the reference to a list and then making a copy of it.

Do consider the idea of returning an iterator to the list (or reference to the iterator) if possible (assuming that the list is not something local to a function etc).

Fanatic23
+1  A: 

There exists RVO. I am not sure if it applies here. Anyways it's one way to minimize copying.

http://en.wikipedia.org/wiki/Return_value_optimization

Ronny