首页 > 解决方案 > Which way to return value works faster in C++?

问题描述

Lets suppose that some function has multiple if statemens, like in the code below. Is there any difference in these two ways of returning some default value? Can anyone tell me about pos and cons of these two approaches?

First:

CustomClass foo(const Param* par)
{
    if (nullptr == par)
        return CustomClass();

    if (!check1(par))
        return CustomClass();

    if (!check2(par))
        return CustomClass();

    // some code

    return CustomClass();
}

Second:

CustomClass foo(const Param* par)
{
    CustomClass ret;
    if (nullptr == par)
        return ret;

    if (!check1(par))
        return ret;

    if (!check2(par))
        return ret;

    // some code

    return ret;
}

Seems it should depends on copiler...

标签: c++c++11

解决方案


两者都是编译器优化的主题。第一个是 URVO(未命名的返回值优化),第二个是 NRVO(命名的返回值优化)。C++ 标准明确允许编译器逃避复制。

[12.8]

当满足某些条件时,允许实现省略类对象的复制/移动构造,即使为复制/移动操作选择的构造函数和/或对象的析构函数具有副作用。

...在具有类返回类型的函数的返回语句中,当表达式是具有相同类型(忽略 cv 限定)的非易失性自动对象(函数参数...除外)的名称时函数返回类型,可以通过将自动对象直接构造到函数调用的返回对象中来省略复制/移动操作

即使没有启用优化,现代版本的 GCC、Clang 和 MSVC 也会在这两种情况下产生相同的组装。这里有些例子:


推荐阅读