首先让我们用最少的代码重现问题:
#include <memory>
class SomeClass;
int main()
{
std::unique_ptr<SomeClass> ptr;
}
错误:
In file included from /opt/gcc-explorer/gcc-6.2.0/include/c++/6.2.0/memory:81:0,
from <source>:1:
/opt/gcc-explorer/gcc-6.2.0/include/c++/6.2.0/bits/unique_ptr.h: In instantiation of 'void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = SomeClass]':
/opt/gcc-explorer/gcc-6.2.0/include/c++/6.2.0/bits/unique_ptr.h:236:17: required from 'std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = SomeClass; _Dp = std::default_delete<SomeClass>]'
<source>:7:30: required from here
/opt/gcc-explorer/gcc-6.2.0/include/c++/6.2.0/bits/unique_ptr.h:74:22: error: invalid application of 'sizeof' to incomplete type 'SomeClass'
static_assert(sizeof(_Tp)>0,
^
Compiler exited with result code 1
这里同样的问题(证明跟继承无关):
#include <memory>
class SomeClass;
class NotDerived
{
// ~NotDerived(); //defined in cpp
std::unique_ptr<SomeClass> ptr;
};
int main(){
NotDerived d;
}
错误:
In file included from /opt/gcc-explorer/gcc-6.2.0/include/c++/6.2.0/memory:81:0,
from <source>:1:
/opt/gcc-explorer/gcc-6.2.0/include/c++/6.2.0/bits/unique_ptr.h: In instantiation of 'void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = SomeClass]':
/opt/gcc-explorer/gcc-6.2.0/include/c++/6.2.0/bits/unique_ptr.h:236:17: required from 'std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = SomeClass; _Dp = std::default_delete<SomeClass>]'
<source>:5:7: required from here
/opt/gcc-explorer/gcc-6.2.0/include/c++/6.2.0/bits/unique_ptr.h:74:22: error: invalid application of 'sizeof' to incomplete type 'SomeClass'
static_assert(sizeof(_Tp)>0,
^
Compiler exited with result code 1
现在让我们记住 unique_ptr 的真正含义:
template<
class T,
class Deleter = std::default_delete<T>
> class unique_ptr;
还有 default_delete ...
在 ptr 上调用 delete
而指针上的delete(指向SomeClass)将要破坏Someclass,因此需要调用SomeClass::~SomeClass
您尚未声明的内容。因此出现错误。
为什么这很重要?
因为在你的代码中,如果你没有为Derived声明析构函数,会生成一个默认的,当然会调用ptr的析构函数。
此时,编译器将需要SomeClass 的完整定义,以便知道如何销毁它。
通过在 Derived 中声明析构函数,您可以将此问题推迟到 Derived::~Derived 的实现。