Moving: what does it take?

c++, c++11, move-semantics, visual-c++, visual-studio-2012

Solution

I hoped it'd be used automatically as v isn't needed after the assignment anymore. Is std::move required in this case?

Movement always must be explicitly stated for lvalues, unless they are being returned (by value) from a function.

This prevents accidentally moving something. Remember: movement is a destructive act; you don't want it to just happen.

Also, it would be strange if the semantics of `name_ = v;` changed based on whether this was the last line in a function. After all, this is perfectly legal code:

name_ = v;
v[0] = 5; //Assuming v has at least one character.

Why should the first line execute a copy sometimes and a move other times?

If so, I might as well use the non-C++11 swap.

You can do as you like, but `std::move` is more obvious as to the intent. We know what it means and what you're doing with it.

Problem

What does it take to use the move assignment operator of std::string (in VC11)? I hoped it'd be used automatically as v isn't needed after the assignment anymore. Is std::move required in this case? If so, I might as well use the non-C++11 swap. ``` #include <string> struct user_t { void set_name(std::string v) { name_ = v; // swap(name_, v); // name_ = std::move(v); } std::string name_; }; int main() { user_t u; u.set_name("Olaf"); return 0; } ```

Original source