Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are return values going to be passed by rvalue reference in c++0x?

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.

like image 619
rlbond Avatar asked Aug 22 '09 20:08

rlbond


2 Answers

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.

like image 170
Johannes Schaub - litb Avatar answered Sep 21 '22 23:09

Johannes Schaub - litb


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.

like image 44
Motti Avatar answered Sep 19 '22 23:09

Motti