如果您的意思是 NRVO(命名返回值优化)而不是 RVO(返回值优化),那么对象必须在函数内部命名。否则,它将仅符合 RVO 资格,而不是 NRVO。因此,将其称为命名返回值优化是有充分理由的。
查看以下示例:
RVO:
BigObject foo(int x, int y)
{
// Returned BigObject is created ad-hoc, and has no local 'name'.
return BigObject(x, y);
}
void bar()
{
BigObject obj = foo(4, 6);
}
会被优化编译器翻译成这个伪代码:
void foo(int x, int y, BigObject& ret)
{
ret._constructor_(x, y);
}
void bar()
{
BigObject obj; // Allocate obj on the stack, but don't construct it just yet!
foo(4, 6, obj); // Now obj is constructed by foo()
}
NRVO:
BigObject foo(int x, int y, int z)
{
// Returned BigObject has a local 'name' in foo(), which is obj.
BigObject obj(x, y);
// Do something with obj
obj.setZ(z);
return obj;
}
void bar()
{
BigObject obj = foo(4, 6, 7);
}
会被优化编译器翻译成这个伪代码:
void foo(int x, int y, int z, BigObject& ret)
{
ret._constructor_(x, y);
// Do something with ret
ret.setZ(z);
}
void bar()
{
BigObject obj; // Allocate obj on the stack, but don't construct it just yet!
foo(4, 6, 7, obj); // Now obj is constructed by foo()
}
请注意,优化是否实际发生在很大程度上取决于编译器。一些编译器(如非常老的编译器)根本不会执行 RVO 或 NRVO,而其他编译器可能对此优化有不同的限制。下面是 MSVC 对 NRVO 的约束的描述:
http://msdn.microsoft.com/en-us/library/ms364057(v=vs.80).aspx#nrvo_cpp05_topic3