Paul
Paul

Reputation: 6861

std::move before assignment in the same expression

Consider the following snippet:

std::string foo(std::string x) {
    x += "!";
    return x;
}
// ...
std::string y = "Hello";
// ...
y = foo(y);

My questions:

Upvotes: 2

Views: 131

Answers (1)

Eugene
Eugene

Reputation: 7188

Does the compiler recognize that y can be moved when passed to foo, since it's going to be assigned into right after that.

No, it is not allowed to do it. std::move() is merely a cast, in this case into std::string&&. Without the cast, std::string::string(const std::string&) constructor signature will be chosen, which is a copy constructor.

If not, is it valid for me to add std::move for passing y to foo: y = foo(std::move(y))? Does it eliminate all copies?

Sure, you can, and it does eliminate all copies. First, argument y is moved into parameter x. On the return, x is moved into y.

Upvotes: 2

Related Questions