考虑这个代码,有一个明显的编译错误:(1)
struct A;
struct B {
B() { new A(); } // error: allocation of incomplete type 'A'
};
Run Code Online (Sandbox Code Playgroud)
使用a unique_ptr也无济于事:(2)
struct A;
struct B {
B() { std::make_unique<A>(); } // error: due to ~unique_ptr()
};
Run Code Online (Sandbox Code Playgroud)
然后(令我惊讶的是)我发现,这将编译:(3)
struct A;
struct B {
B() { std::make_unique<A>(); }
};
struct A {}; // OK, when a definition is added **below**
Run Code Online (Sandbox Code Playgroud)
然后我检查了,这是否有帮助new- 不:(4)
struct A;
struct B {
B() { new A(); } // error: allocation of …Run Code Online (Sandbox Code Playgroud)