【发布时间】:2014-03-07 13:15:53
【问题描述】:
#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、clang++ 3.0 在 Ubuntu 上):
Constructed #0
Exiting f()
Exiting main()
Destructed #0
我猜测没有调用复制构造函数(尽管它具有可观察到的副作用),并且对象 a 没有在 f() 中被销毁)是 NRVO(类似情况,如:https://stackoverflow.com/a/3906038/1857518 中所述)。
我的问题:
- 这个程序的输出是否符合 C++ 标准?
- 如果 (1) 为真,那么它属于以下哪种情况:
- 输出将永远是这个
- 存在一组合法且有限的输出,例如
Out(例如|Out| > 1)。并且一致的编译器可以从集合Out中生成任何一个。如果是这样的话,Out的集合是什么样子的。
【问题讨论】:
标签: c++