小编h4s*_*ssi的帖子

当包装在模板中时,新的不完整类型编译

考虑这个代码,有一个明显的编译错误:(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)

c++ templates forward-declaration

10
推荐指数
1
解决办法
548
查看次数

标签 统计

c++ ×1

forward-declaration ×1

templates ×1