Pan
Pan

Reputation: 155

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 ?

Upvotes: 4

Views: 588

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473457

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.

Upvotes: 5

Related Questions