【发布时间】:2015-05-13 12:05:27
【问题描述】:
我有以下示例代码:
#include <iostream>
using namespace std;
struct foo {
foo() { cout << "foo constructed.\n"; }
~foo() { cout << "foo destroyed.\n"; }
};
struct bar {
bar(foo t=foo{}) { }
};
int main(int argc, char **argv) {
bar X[2]{};
return 0;
}
当我用 clang++ -std=c++11 test.cc 编译它时,程序会产生以下输出:
foo constructed.
foo constructed.
foo destroyed.
但我预计会有一个额外的“foo 被破坏”。在两个“foo 构造”之间。线。为什么只有一个 foo 被销毁? clang 3.5.1 和 3.6.0 都会出现这种情况。
【问题讨论】:
-
GCC 4.9 输出
foo constructed. foo destroyed. foo constructed. foo destroyed.Clang 3.5 和 3.6 会重现您的结果。我猜这是 clang 中的一个错误(使用 libstdc++ 和 clang 仍然会产生错误的结果,所以我不认为这是一个标准库问题)。 -
试试
endl而不是\n。 -
@zenith:程序结束时会刷新流,老兄!
-
如果没有人尝试,将
[2]替换为[10],结果类似; 10 次建设,但仍然是 1 次破坏。 (OS X 铿锵声 3.5)。此外,通过删除{}进行测试。我特别喜欢这种差异。 -
FWIW,goo.gl/fkw6dq