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.
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
andgcc
, but notMSVC
, further cementing that this is an implementation-defined optimization.§12.8/31 describes copy elision: