Why does the returned value need to be the first declared local for NRVO?

131 views Asked by At

It is my understanding that for the compiler to be able to do Named Return Value Optimization (NRVO) the return value must be declared before any others in the function body. I suspect this may be due to the order of stack unwinding in the event of an exception but im not sure. What is the reason that the named return value must be the first declared in the function body?

class C{};
C f(){
    C ret; //NRVO possible
    return ret;
}
C g(){
    int i;
    C ret;  //NRVO not possible?
    return ret;
}

use case:

auto c = f();
auto c2 = g();

Edit: Thank you all answerers for helping me understand this, I am beginning to suspect that Chandler Carruth's statement here:http://www.youtube.com/watch?v=fHNmRkzxHWs minute 32:30 may be misleading and/or I just misunderstand it. It does not seem to be important that the return variable be declaired first.

1

There are 1 answers

0
AudioBubble On BEST ANSWER

The standard imposes no requirements on the order of declarations/definitions for variables in regards to copy elision. Note that the standard says "an implementation is allowed", not that it should, shall, etc. We can see that copy elision occurs for clang and gcc, but not MSVC, further cementing that this is an implementation-defined optimization.

§12.8/31 describes copy elision:

[..] This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):

— in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value

[..]