要使用NRV优化的函数遵循什么规则 [英] What rules to follow for a function to use NRV optimization
问题描述
我应该遵循哪些规则或提示来启用函数在函数中使用NRV(命名返回值)优化?我从不同的地方吸收了这些提示,但不知道我的理解是否正确:
What rules or tips should I follow to enable a function to use NRV (named return value) optimization in a function? I assimilated these tips from different places, but don't know if it my understanding is correct:
- 要返回的对象不应该
- 返回语句应该有括号括起来的对象
- 对象到函数中的任何名称(为什么它被称为NAMED返回值优化!!)
- the object to be returned should not have any name inside the function (then why is it called NAMED return value optimization!!)
- return statement should have object surrounded by parenthesis
- object to be returned should have explicit and inline copy constructor
如果您的意思是NRVO(Named Return Value),那么返回值应该是明确的和内联的拷贝构造函数
推荐答案
查看以下示例:
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);
}
将由优化编译器转换为此伪代码:
Would be translated by an optimizing compiler to this pseudo-code:
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:
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);
}
将由优化编译器转换为此伪代码:
Would be translated by an optimizing compiler to this pseudo-code:
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
Note that whether the optimization actually occurs depends a lot on the compiler. Some compilers (like very old compilers) won't do RVO or NRVO at all, while other compilers may have different constraints on this optimization. Here's a description of the constraints MSVC puts on NRVO: http://msdn.microsoft.com/en-us/library/ms364057(v=vs.80).aspx#nrvo_cpp05_topic3
这篇关于要使用NRV优化的函数遵循什么规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!