Reputation: 14583
Assume I have a class called Foo that has suitable move constructors/assignment operators defined. Given the following pseudocode:
Foo some_func(Foo var) {
<update var>
return var;
}
int main() {
Foo var;
var = some_func(var);
}
Will C++11 automatically use move semantics when passing var to some_func, and again to re-assign to var, since the original value of var would be destroyed anyways? I think this would be a safe optimization and it would let you write pure functions that are as fast as passing references/pointers. If it can't do it, why not? I know it can be forced with std::move but it'd be cool if it was automatic.
Upvotes: 1
Views: 126
Reputation: 171491
Will C++11 automatically use move semantics when passing var to some_func,
No, that is a copy construction, because var
is an lvalue.
The language does not allow the compiler to do anything else. The only time an lvalue is implicitly moved instead of copied is when returning it from a function, e.g. this line in some_func
will use the move constructor:
return var;
and again to re-assign to var, since the original value of var would be destroyed anyways?
That will use Foo's move assignment operator, because it's assigning an rvalue to var
.
You would avoid any copies if you used some_func(std::move(var))
or if you wrote it like this instead:
Foo var = some_func({});
This creates a temporary which initializes the function argument, then returns the function parameter, which will use a move, then var
will be move-constructed, but the move can be elided. So the compiler is allowed to perform only a default construction for the function parameter and a move construction for var
.
Upvotes: 5