Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::move called on a prvalue deconstruct the object?

I 've wrote such code applying std::move to a prvalue from a temporary constructor.

  // a std::string instance in class Obj

  Obj&& myObj1 = std::move(Obj(1,"lost"));
  print(myObj1);

  Obj&& myObj2 = Obj(2,"keep");
  print(myObj2);

And the print effects is like that (print also in constructor and destructor):

Construct lost
Destroy lost
obj1: 

Construct keep
obj2: keep
Destroy keep

Some questions in stackoverflow say there should be no effect for the first case, I wonder what happens in my code. Is that the Obj(1, "lost") in the std::move function as argument and dies when std::move exit ?

like image 896
Pan Avatar asked Nov 15 '25 17:11

Pan


1 Answers

std::move is a function call; it's not a magical operator of C++. All it does is return a reference to the object it is given. And it takes its parameter by reference.

In C++, if you have a prvalue, and you pass it to a function that takes a reference to it, the temporary created by that prvalue will only persist until the end of the expression.

So move returns a reference to the temporary. But that temporary will be destroyed immediately after myObj1 is initialized. So myObj1 is a reference to a destroyed object.

like image 142
Nicol Bolas Avatar answered Nov 17 '25 09:11

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!