Let's say I have a function:
typedef std::vector<int> VecType;
VecType randomVector();
int processing()
{
VecType v = randomVector();
return std::accumulate(v.begin(), v.end(), 0);
}
Does C++0x specifically say the spurious copy will be averted from the return value of randomVector? Or would a compiler need to implement the RVO? It seems to me like the value randomVector()
should be treated as an rvalue, and thus v's move constructor should be called, but I'm not completely sure this is true.
The rule is the following
Like you say, the temporary is an rvalue, and thus the move constructor is selected, because of a rule in 13.3.3.2/3
, which says that a rvalue reference binds to an rvalue better than an lvalue reference. In deciding whether to use the move or the copy constructor, overload resolution will therefor prefer the move constructor.
The rule that the compiler is allowed to perform RVO is written at 12.8/15
.
All return values are considered to be rvalues
so if the compiler doesn't implement RVO on this case it must use the move constructor rather than the copy constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With