2

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 ?

xskxzr
  • 12,442
  • 12
  • 37
  • 77
Pan
  • 125
  • 2
  • 5
  • 1
    `Obj(1,"lost")` _is_ an rvalue. `std::move` will cast it to an rvalue, so it's effectively a no-op. Please, post a [repro]. – Enlico Sep 05 '21 at 05:12
  • @Enlico Sorry, I have read the page and imitated other posts,in this case does it means I should provide a minimal compileable codes instead missing the detail? – Pan Sep 05 '21 at 05:51
  • 1
    Your code is not usable as it is. Make it such that one can copy, paste, compile, and run. – Enlico Sep 05 '21 at 05:52
  • FYI The amount of code in the question is just fine to support the question. It would be nice to have a compile-ready complete example in addition (some offsite location like github or pastebin is fine for compile-ready demos, since the question is still fully valid even if the link breaks). The question would be substantially more difficult to read if it started with a full program instead of just the lines of interest. – Ben Voigt Dec 13 '22 at 22:36

1 Answers1

3

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 1
    @bloody: If a function takes a parameter by value, a prvalue (in C++17) does not create a temporary. It initializes the parameter directly. So only functions which take references will generate a temporary. The lifetime of by-value parameters works out to something similar, but they're not the same. – Nicol Bolas Dec 14 '22 at 20:50
  • OK, Thanks for explanation. Btw. you could have clarified this after my first edition to avoid another edition/rejection/clicking and further confusion ;) – bloody Dec 17 '22 at 11:00