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?
3
  • 1
    Does this answer your question? What is std::move(), and when should it be used? Commented Jun 29, 2020 at 16:47
  • 1
    Thanks. I read through that. Based on what I understand nothing will happen to s? Is that the answer? Commented Jun 29, 2020 at 16:52
  • @guarav yes, exactly. Commented Jun 29, 2020 at 16:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 Coincidentally, I was thinking of template<typename T> std::decay_t<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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.