Consider the following code snippet:
list<someClass>& method();
....
list<someClass> test = method();
What will the behavior of this be? Will this code:
-
Return a reference to the someClass instance returned by return value optimization from method(), and then perform someClass’s copy constructor on the reference?
-
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…
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 variabletest.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
testa reference:However,
testwill then refer to the original list, so any modifications made totestwill also be made to the original list, and whenever the original list is destroyed,testwill become invalid (which means you have to be more careful with object lifetimes).