How to move temporary object without std::move [duplicate]

  • A+

This question already has an answer here:

Move constructor of class accepts rvalue reference which can be reference to temporary object. So, i have temporary object and appropriate move constructor which can accept reference to temporary object, but move constructor does not called. What`s wrong?

    //g++  5.4.0  #include <iostream>  class foo {     int data; public:     foo(int v) : data(v) {std::cout << "foo(int)/n";}      foo(foo&& f)     {         std::cout << "moved/n";     }      void print()     {         std::cout << data;     } };  void acceptTmp(foo f) {     f.print(); }  int main() {     foo f1 = foo(100);     f1.print();     acceptTmp(foo(200)); //also does not move } 


What`s wrong?

Nothing is wrong, except for your expectation that the move constructor would be called.

Prior to C++17, the temporary object would indeed be moved into the argument from the point of view of the abstract machine. However, the standard allows the move to be elided by the compiler, by constructing the temporary directly in place of the object where it would be moved into. You cannot rely on the side-effects of the move constructor to occur.

Post C++17, there is no temporary object or move involved. The standard guarantees that the argument is constructed in place.

The lack of a move is a good thing. Moving an object is potentially slower than not moving it.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: