小编mic*_*jan的帖子

为什么在堆数组初始化中调用了两次复制构造函数?

对于以下 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)

c++ g++ copy-constructor clang++ c++14

15
推荐指数
1
解决办法
514
查看次数

标签 统计

c++ ×1

c++14 ×1

clang++ ×1

copy-constructor ×1

g++ ×1