My head hurts: I read so many blogs about the semantics of C ++ 11x displacement that my brain became soft, so please can someone give me a short but sweet guide on how to make the following code effective? Given the Foo
class, I want to be able to write functions that return Foo
objects in different states (sometimes called source functions), and do this as efficiently as possible.
class Foo { // Some methods and members }; Foo getFirstFoo() { Foo foo; // Do some things to foo return foo; } Foo getSecondFoo() { Foo foo; // Do some different things to foo return foo; } int main() { Foo f = getFoo(); // use f ... f = getSecondFoo(); // use f ... return 0; }
I donโt want to change Foo
much, and the idea is to allow the creation of all kinds of Foo
objects using various member functions that are not members, so adding an even greater number of constructors will be missing a point.
In C ++ 03, my options are to wrap the returned object in auto_ptr
(the big drawback is that the recipient code must know to handle the smart pointer) or cross my fingers and hope that some optimization may happen (probably for the first line in main
, especially for the second). C ++ 11x seems to provide something better thanks to move semantics, but how can I use them? So I need to change the way objects return to their original functions or add a move constructor to Foo
or both?
source share