2

What happens when I just use std::move without any assignment?

std::string s = "Moving";
std::move(s);  //What happens on this line to s?
//is s still valid here?
JFMR
  • 23,265
  • 4
  • 52
  • 76
Gaurav
  • 744
  • 5
  • 8

1 Answers1

8

std::move() doesn't move the passed object by itself; it just possibly enables move semantics for the object. It consists of a cast whose result you can use to select – if possible – the proper overload that supports move semantics. Therefore, in your code:

std::string s = "Moving";
std::move(s);

std::move(s) above casts s to an rvalue reference. The result of the casting is not used. The object s above is not actually moved, and it isn't modified.

JFMR
  • 23,265
  • 4
  • 52
  • 76
  • On my team, we take the extreme position that if `std::move` is used on something, treat it as if the rvalue reference was exploited. Even in situations that you know the rvalue was not exploited, such as in this case. (But in this case, it'd get dinged in the code review for being a purposeless no-op.) – Eljay Jun 29 '20 at 17:26
  • 1
    @Eljay Coincidentally, I was thinking of `template std::decay_t steal_state(T&& arg) { return std::move(arg); }` for enforcing move even if the returned value is not used. Since `steal_state()` returns the object *by value*, and that object is *moved constructed* from `arg`, it moves the argument passed (provided it is not `const`-qualified). – JFMR Jun 29 '20 at 17:40