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

Will RVO work in this case?

我不确定我是否应该打扰,因为它不是任何安全关键应用程序,但我只是好奇并且自己无法弄清楚:编译器会为以下方法应用 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 class 没有实现移动构造函数和移动赋值运算符。我在 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".

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