gpt4 book ai didi

c++ - 为什么返回值优化发生在这里

转载 作者:行者123 更新时间:2023-11-30 01:50:44 24 4
gpt4 key购买 nike

来自 this张贴状态

When a nameless temporary, not bound to any references, would be moved or copied into an object of the same cv-unqualified type, the copy/move is omitted. When that temporary is constructed, it is constructed directly in the storage where it would otherwise be moved or copied to. When the nameless temporary is the argument of a return statement, this variant of copy elision is known as RVO, "return value optimization".

所以为了测试这个概念,我尝试了以下实验

class C
{
public:
C()
{
std::cout << "Constructor of C." << std::endl;
}
C(const C &)
{
std::cout << "Copy-constructor of C." << std::endl;
}
};

C func()
{
const C c;
return c; //c is not a nameless and is not CV unqualified as it is a const type.
}

int main(int argc, char **argv)
{
C c = func();
}

输出:C的构造函数

我期待:C的构造函数C 的复制构造函数C 的拷贝构造函数

我的问题是为什么要在这里进行返回值优化?

最佳答案

因为你引用了一个不相关的段落。相关的就是上面那个(出处相同):

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 the function parameter, or a catch clause parameter, and which has the same cv-unqualified type as the return type of the function, then copy/move is omitted.

任何规定的条件都允许复制省略。

关于c++ - 为什么返回值优化发生在这里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27098070/

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