对于以下 C++14 代码,为什么 g++ 生成的代码new A[1]{x}似乎调用了复制构造函数两次?
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "default ctor" << endl; }
A(const A& o) { cout << "copy ctor" << endl; }
~A() { cout << "dtor" << endl; }
};
int main()
{
A x;
cout << "=========" << endl;
A* y = new A[1]{x};
cout << "=========" << endl;
delete[] y;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译和输出:
$ g++ -fno-elide-constructors -std=c++14 test.cpp && ./a.out
default …Run Code Online (Sandbox Code Playgroud)