Is there language level optimization like RVO and NRVO?

384 views Asked by At

RVO is a compiler optimization but can provide a really useful performance boost. However it is not guaranteed and cannot be relied on.

Is there anything in the language standard itself can optimize return value? Move semantics still copies the members values, correct?

2

There are 2 answers

4
Erik van Velzen On BEST ANSWER

I don't know if I misunderstood your question, but (N)RVO is in fact "in the language standard itself". This is called copy elision and described in ยง12.8.31.

Indeed move construction is more computationally expensive than RVO, because as you said it still has to "copy" the member variables from one memory location to another (shallow copy of the object). RVO eliminates these read/write actions entirely.

(N)RVO works in the majority of cases, and where it can't (when a function can return one of multiple variables) move construction kicks in.

AFAIK there is a consensus that all cases of "optimizing return value" as you call it are sufficiently covered since C++11

2
Yakk - Adam Nevraumont On

C++11 has the guarantee of implicit move when returning from a function in certain ways.

In addition, you can directly construct the return value using any implicit constructor via return {a,b,c}; syntax.

Finally, rvo if it fails becomes an implicit move, and the first implicit move above is often turned into nrvo, so the techniques align nicely.