gpt4 book ai didi

c++ - 为什么 Visual C++ 不对最琐碎的代码执行返回值优化?

转载 作者:IT老高 更新时间:2023-10-28 22:59:29 25 4
gpt4 key购买 nike

Visual C++ 不执行返回值优化吗?

#include <cstdio>
struct Foo { ~Foo() { printf("Destructing...\n"); } };
Foo foo() { return Foo(); }
int main() { foo(); }

我编译并运行它:

cl /O2 test.cpp
test.exe

然后打印出来:

Destructing...
Destructing...

为什么它不执行 RVO?

最佳答案

当我用这个测试时:

#include <iostream>
struct Foo {
Foo(Foo const &r) { std::cout << "Copying...\n"; }
~Foo() { std::cout << "Destructing...\n"; }
Foo() {}
};

Foo foo() { return Foo(); }

int main() { Foo f = foo(); }

...我得到的输出是:

Destructing...

没有调用复制构造函数,只有一个析构函数。

关于c++ - 为什么 Visual C++ 不对最琐碎的代码执行返回值优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11730354/

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