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;
}
3. Don't Leave Drawers Full of Belongings. Please empty your desk and dresser drawers before moving day. It's natural to think that your drawers are technically like “boxes” themselves, but moving heavy furniture is hard enough when it's empty, so imagine how much heavier a dresser is when the drawers are full!
Pack Decor & Books Items that are in your home purely for aesthetic purposes are good items to pack first when moving. This might include artwork, decor, books, magazines, and the like. These items are easy to pack first because chances are you won't need them during the move or the weeks preceding it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With