c++ - RVO 在这种情况下会起作用吗?

标签 c++ qt copy-elision rvo

我不确定我是否应该打扰,因为它不是任何安全关键应用程序,但我只是好奇并且自己无法弄清楚:编译器会为以下方法应用 RVO 吗?

QJsonObject MyClass::buildObject(const QVector2D& position, const QString& id) const
{
    QJsonObject retObject {
        {"Position", QJsonArray{position.x(), position.y()}},
    };

    if (!id.isNull() && !id.isEmpty())
    {
        retObject.insert("Id", id);
    }

    return retObject;
}

QJsonObject 类不实现移动构造函数和移动赋值运算符。我在 Ubuntu 下通过 Qt 5.9 使用 GCC 5.4 (--std=c++14)。

最佳答案

编译器可以在这里做RVO,但不是必须的,cf. cppreference

If a function returns a class type by value, and the return statement's expression is the name of a non-volatile object with automatic storage duration, which isn't a function parameter, or a catch clause parameter, and which has the same type (ignoring top-level cv-qualification) as the return type of the function, then copy/move (since C++11) is omitted. When that local object is constructed, it is constructed directly in the storage where the function's return value would otherwise be moved or copied to. This variant of copy elision is known as NRVO, "named return value optimization".

因此编译器无法在返回时优化复制 retObject,但它可以省略创建临时返回值对象,而是直接将 retObject 复制到任何 MyClass::BuildObject 已分配。

关于c++ - RVO 在这种情况下会起作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51594346/

相关文章:

c++ - 与我的 Qt 应用程序一起工作的轻量级跨平台数据库引擎

c++ - 为什么我不能通过 std::tuple 获得保证的复制省略?

c++ - 拷贝初始化是否与拷贝的拷贝初始化相同?

c++ - std::add_pointer,try_add_pointer 在可能的实现中有什么用?

c++ - 在 Qt 中创建的 GUI 滞后(由 QTime 验证)

c++ - 更改字符集后 MFC 应用程序的视觉外观发生变化

qt - 使用 Qt 的 QProcess 作为 popen(使用 ffmpeg rawvideo)

c++ - 无法将 int {Class}::* 转换为 int*

python - 增加QtWebKit每台主机的最大连接数

c++ - 映射迭代器对值的复制省略