gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:58:40 29 4
gpt4 key购买 nike

我不确定我是否应该打扰,因为它不是任何安全关键应用程序,但我只是好奇并且自己无法弄清楚:编译器会为以下方法应用 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com