Will return values ​​be passed using 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 indicate that a false copy will be prevented from the return value of randomVector? Or should the compiler implement RVO? It seems to me that the value of randomVector() should be considered as an rvalue, and therefore it is necessary to call the v move constructor, but I'm not entirely sure that this is true.

+6
c ++ c ++ 11 rvalue-reference return-value-optimization return-value
source share
2 answers

The rule is as follows

  • If the compiler can perform RVO, it is allowed to do this, and copying and moving is not performed.
  • Otherwise, the corresponding constructor is executed.

As you say, the rvalue is temporary, and therefore the move constructor is chosen because of the rule in 13.3.3.2/3 , which says that the rvalue reference binds to the rvalue better than the lvalue reference. When deciding whether to use a move or a copy constructor, overload resolution will be the preferred move constructor for this.

The rule that the compiler is allowed to run RVO is recorded in 12.8/15 .

+7
source share

All return values ​​are considered rvalues , so if the compiler does not implement RVO in this case, it should use a move constructor, not a copy constructor.

+2
source share

All Articles