要使用NRV优化的函数遵循什么规则 [英] What rules to follow for a function to use NRV optimization

查看:289
本文介绍了要使用NRV优化的函数遵循什么规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该遵循哪些规则或提示来启用函数在函数中使用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:


  1. 要返回的对象不应该

  2. 返回语句应该有括号括起来的对象

  3. 对象到函数中的任何名称(为什么它被称为NAMED返回值优化!!)
  1. the object to be returned should not have any name inside the function (then why is it called NAMED return value optimization!!)
  2. return statement should have object surrounded by parenthesis
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆