Reputation: 6861
Consider the following snippet:
std::string foo(std::string x) {
x += "!";
return x;
}
// ...
std::string y = "Hello";
// ...
y = foo(y);
My questions:
y
can be moved when passed to foo
, since it's going to be assigned into right after that.std::move
for passing y
to foo
: y = foo(std::move(y))
? Does it eliminate all copies?Upvotes: 2
Views: 131
Reputation: 7188
Does the compiler recognize that
y
can be moved when passed tofoo
, 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 passingy
tofoo
: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