gpt4 book ai didi

c++ - NRVO - 该程序的输出是否定义明确?

转载 作者:行者123 更新时间:2023-11-30 04:07:44 25 4
gpt4 key购买 nike

#include <iostream>
using namespace std;

int gc = 0;
struct A {
int id;
A():id(gc++) { cout << "Constructed #" << id << "\n"; }
A(const A& b):id(gc++) { cout << "Copying from " << b.id << " to " << id << "\n"; }
~A() { cout << "Destructed #" << id << "\n"; }
};
A f() {
A a;
cout << "Exiting f()" << "\n";
return a;
}
int main() {
A b = f();
cout << "Exiting main()" << "\n";
return 0;
}

生成的输出(没有优化 (-O0),并使用以下任一编译器:g++ 4.6.3、g++ 4.8.1、Ubuntu 上的 clang++ 3.0:

Constructed #0
Exiting f()
Exiting main()
Destructed #0

我猜测复制构造函数没有被调用(尽管它有可观察到的副作用),并且对象 a 没有在 f() 中被销毁)是 NRVO(类似情况如中所述:https://stackoverflow.com/a/3906038/1857518)。

我的问题:

  1. 这个程序的输出是否符合 C++ 标准?
  2. 如果(1)为真,那么是下列情况中的哪一种:
    • 输出总是这样
    • 存在一组合法且有限的输出,例如 Out(例如 |Out| > 1)。并且符合规范的编译器可以生成 Out 集合中的任何一个。如果是这种情况,集合 Out 看起来像什么。

最佳答案

您在此行为中看到的称为 copy elision .

1.Is the output of this program well specified by C++ standards?

是的,允许编译器针对这种情况优化复制副作用。

2.The output will always exactly be this

没有。如前所述,编译器允许优化复制行为,但不一定需要这样做。

因此,对于返回的“拷贝”,您不能依赖任何已存在或已移除的副作用。另见这篇文章:Is it possible to ensure copy elision?

关于c++ - NRVO - 该程序的输出是否定义明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22239374/

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