Question

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.

Was it helpful?

Solution

The rule is the following

  • If the compiler can do RVO, then it is allowed to do it, and no copy and no move is made.
  • Otherwise, the appropriate constructor is taken.

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top