只要我不将构造函数的定义(B
)移动到标头B.h
,代码就会工作。Pimpl with unique_ptr:为什么我必须将接口的构造函数的定义移动到“.cpp”?
B.h
class Imp; //<--- error here
class B{
public:
std::unique_ptr<Imp> imp;
B(); //<--- move definition to here will compile error
~B();
//// .... other functions ....
};
B.cpp
#include "B.h"
#include "Imp.h"
B::B(){ }
~B::B(){ }
Imp.h
class Imp{};
中号ain.cpp(编译我)
#include "B.h"
Error: deletion of pointer to incomplete type
Error: use of undefined type 'Imp' C2027
我能以某种方式了解到,析构函数必须转移到.cpp
,因为解构的Imp
可能被称为: -
delete pointer-of-Imp; //something like this
然而,我不明白为什么规则还涵盖构造函数(问题)。
我已阅读: -
- Deletion of pointer to incomplete type and smart pointers
说明原因析构函数需要在.cpp
。 - std::unique_ptr with an incomplete type won't compile
有关默认析构函数的警告。
它是重要的*析构函数*。 –
@Kerrek SB构造函数没有关系? – javaLover
OT:把'Imp'放在'B'里面;和'class ... {public:'=='struct {' –