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;
}
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:Why should the first line execute a copy sometimes and a move other times?
You can do as you like, but
std::moveis more obvious as to the intent. We know what it means and what you’re doing with it.