Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving: what does it take?

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;
}
like image 461
XTF Avatar asked May 07 '12 21:05

XTF


People also ask

Do I need to empty drawers for movers?

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!

What should be moved first when moving?

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.


1 Answers

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.

like image 181
Nicol Bolas Avatar answered Oct 29 '22 13:10

Nicol Bolas