RVO, moving semantics and fighting against optimal code

If I get it right, moving semantics allows you to move and reuse resources from temporary, unnamed objects. RVO, although the previous semantics of the move goes further and "steals" the entire object to avoid an additional call to the constructor and assign / copy.

It seems a little intuitive to me, isn’t it faster, simpler and more understandable to the user if the called constructor directly uses the address of the final destination lvalue to directly place the data where the user needs it?

I mean, “creating this object in this place” seems a little more intuitive than “creating this object somewhere and then copy it to the right place.”

+6
source share
1 answer

Yes, this is a "bit counter intuitive." With copy permission, all side effects of the constructor are allowed.

#include <iostream> struct X { X() { std::cout << "Construct" << std::endl; } X(X&&) { std::cout << "Move" << std::endl; } ~X() { std::cout << "Destruct" << std::endl; }; }; X f() { return X(); } int main() { X x(f()); return 0; } 

Copy elision: g ++ -std = C ++ 11 src-test / main.cc

 Construct Destruct 

No copy: g ++ -std = C ++ 11 -fno-elide-constructors src-test / main.cc

 Construct Move Destruct Move Destruct Destruct 

The compiler, knowing the hardware that the program / library creates, can use (optionally) a copy of elision. C ++ itself does not know about hardware return mechanisms. Therefore, it is not possible to build on a specific address in this context.

+7
source

All Articles