Writing the original function in C ++ 11 is correct

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?

+4
source share
1 answer

This is already optimal 1 , provided that the move constructors are generated 2 :

 class Foo { public: Foo(Foo&&) = default; Foo& operator=(Foo&&) = default; }; 

The default values โ€‹โ€‹returned refer to rvalue values.


1 Good ... provided that your Foo class will benefit from the move construct altogether. Remember that moving is copy optimization . Some copies cannot be improved! For example, inappropriate:

 struct Foo { int data; }; struct Foo2 { int data[5<<10]; }; 

fits good:

 struct Foo3 { std::vector<std::string> data; }; 

See Move semantics - what is it? for a more general background on such things.


2 Not all compilers still support this (even if they implement rvalue references), so you may need to write

  • move constructor
  • move destination
+6
source

Source: https://habr.com/ru/post/1382671/


All Articles