6

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;
}
8
  • 2
    I don't see a move constructor anywhere?
    – Corbin
    May 7, 2012 at 21:29
  • @NicolBolas: That's not remotely related to this question. He's asking about moving a std::string member of his class. He's not trying to move the class. May 7, 2012 at 21:37
  • @MooingDuck: Oh. Well, never mind then. I can't really do much about the close vote though... May 7, 2012 at 21:38
  • @Corbin: Eh? std::string should have move-assignment, shouldn't it?
    – XTF
    May 7, 2012 at 21:38
  • 2
    @XTF: Corbin (and two others) misunderstood your question and thought you were trying to move user_t. Please clarify the question. May 7, 2012 at 21:40

3 Answers 3

11

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.

3
  • Move is basically an optimization of copy. Hence, it'd be nice if the compiler automatically performs this optimization if it detects it's safe to do so.
    – XTF
    May 7, 2012 at 21:53
  • @XTF: That would make it difficult to know what code is going to do, whether it will call a copy or move constructor. Elision already does something similar, but it happens only in very specific circumstances. And even then, when elision doesn't happen, you still know exactly which constructor gets called. May 7, 2012 at 22:08
  • The rule you need to keep in mind here is that anything with a name is an lvalue and implicit movement can only be done to rvalues. May 8, 2012 at 0:00
7

The accepted answer is a good answer (and I've upvoted it). But I wanted to address this question in a little more detail:

The core of my question is: Why doesn't it pick the move assignment operator automatically? The compiler knows v isn't used after the assignment, doesn't it? Or does C++11 not require the compiler to be that smart?

This possibility was looked at during the design of move semantics. At an extreme, you might want the compiler to do some static analysis and move from objects whenever possible:

void set_name(std::string v)
{
    name_ = v;  // move from v if it can be proven that some_event is false?
    if (some_event)
       f(v);
}

Ultimately demanding this kind of analysis from the compiler is very tricky. Some compilers may be able to make the proof, and others may not. Thus leading to code that isn't really portable.

Ok, so what about some simpler cases without if statements?

void foo()
{
    X x;
    Y y(x);
    X x2 = x;  // last use?  move?
}

Well, it is difficult to know if y.~Y() will notice x has been moved from. And in general:

void foo()
{
    X x;
    // ...
    // lots of code here
    // ...
    X x2 = x;  // last use?  move?
}

it is difficult for the compiler to analyze this to know if x is truly no longer used after the copy construction to x2.

So the original "move" proposal gave a rule for implicit moves that was really simple, and very conservative:

lvalues can only be implicitly moved from in cases where copy elision is already permissible.

For example:

#include <cassert>

struct X
{
    int i_;
    X() : i_(1) {}
    ~X() {i_ = 0;}
};

struct Y
{
    X* x_;
    Y() : x_(0) {}
    ~Y() {assert(x_ != 0); assert(x_->i_ != 0);}
};

X foo(bool some_test)
{
    Y y;
    X x;
    if (some_test)
    {
        X x2;
        return x2;
    }
    y.x_ = &x;
    return x;
}

int main()
{
    X x = foo(false);
}

Here, by C++98/03 rules, this program may or may not assert, depending on whether or not copy elision at return x happens. If it does happen, the program runs fine. If it doesn't happen, the program asserts.

And so it was reasoned: When RVO is allowed, we are already in an area where there are no guarantees regarding the value of x. So we should be able to take advantage of this leeway and move from x. The risk looked small and the benefit looked huge. Not only would this mean that many existing programs would become much faster with a simple recompile, but it also meant that we could now return "move only" types from factory functions. This is a very large benefit to risk ratio.

Late in the standardization process, we got a little greedy and also said that implicit move happens when returning a by-value parameter (and the type matches the return type). The benefits seem relatively large here too, though the chance for code breakage is slightly larger since this is not a case where RVO was (or is) legal. But I don't have a demonstration of breaking code for this case.

So ultimately, the answer to your core question is that the original design of move semantics took a very conservative route with respect to breaking existing code. Had it not, it would surely have been shot down in committee. Late in the process, there were a few changes that made the design a bit more aggressive. But by this time the core proposal was firmly entrenched in the standard with a majority (but not unanimous) support.

5

In your example, set_name takes the string by value. Inside set_name, however, v is an lvalue. Let's treat these cases separately:

user_t u;
std::string str("Olaf");    // Creates string by copying a char const*.
u.set_name(std::move(str)); // Moves string.

Inside set_name you invoke the assignment operator of std::string, which incurs an unnecessary copy. But there is also an rvalue overload of operator=, which makes more sense in your case:

void set_name(std::string v)
{
    name_ = std::move(v);
}

This way, the only copying that takes place is the string constrution (std::string("Olaf")).

6
  • Moving an argument passed by value here makes no sense. You're avoiding one copy, but you have already copied the initial string into the argument passed by value.
    – mfontanini
    May 7, 2012 at 21:40
  • 1
    @fontanini: it's a common option because it's fairly performant for both passing by rvalue and lvalue both, in one function. May 7, 2012 at 21:41
  • 3
    To expand @MooingDuck's answer: By using just value semantics, it's up to the caller to decide whether to incur a move or copy.
    – mavam
    May 7, 2012 at 21:42
  • Ha, missed that std::move on the "str" argument ;)
    – mfontanini
    May 7, 2012 at 21:43
  • 1
    @XTf: Inside set_name, v is an lvalue. You need to "cast" it to an rvalue via std::move explicitly to select the appropriate overload.
    – mavam
    May 7, 2012 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.