在我在VS2010中运行此代码时,NRVO未被应用。
#include <stdio.h>
class A
{
public:
A() { printf( "I am in constructor\n" ); }
A(const A& a) { printf( "I am in copy constructor\n" ); }
~A() { printf( "I am in destructor\n" ); }
int i;
};
A f(int j)
{
A a;
if ( j ) return a;
a.i = j;
return a;
}
int main()
{
A a;
a = f(5);
}
编辑:这与析构函数有关。当我注释掉它的代码行时,将使用NRVO(命名返回值优化)。但为什么会这样呢?
if
替换为:if (!j) a.i = j;
,这样它就有更高的被应用的可能性。 - David Rodríguez - dribeas