使用unique_ptr <t>进行正向清除会导致C2027和C2338

时间:2019-05-07 09:50:48

标签: c++ unique-ptr

这是简单的代码版本:

//Outer.h
class Inner;

class Outer
{
    std::unique_ptr<Inner> m_ptr;
public:
    ~Outer();
}

//----------------------------------------
//Outer.cpp
#include "Outer.h"
#include "Inner.h"  //here is the full definition of class Inner

Outer::~Outer(){};

//----------------------------------------
//main.cpp
#include "Outer.h"

int main()
{
    Outer b;
    return 0;
}

当我编译“ main.cpp”时,编译器返回C2338(无法删除不完整的类型)和C2027(使用未定义的类型“ Inner”)

我已经读过Is std::unique_ptr required to know the full definition of T? ,并且知道如果我在“ main.cpp”中包含“ Inner.h”,则可以解决此问题。但是为什么呢?

对于原始指针,我可以简单地在头文件(Outer.h)中使用前向清除,在cpp文件(Inner.h)中包含实现(Outer.cpp),在析构函数中手动将其删除,并且只要我使用它,就无需再次包含实现。

但是对于unique_ptr,类似地,我在头文件(Outer.h)中使用前向清除,在cpp文件(Inner.h)中包含实现(Outer.cpp),在destructor(并使用默认析构函数),但是为什么我在使用它时需要再次包含内部类的实现(Inner.h)?

1 个答案:

答案 0 :(得分:2)

您需要在.cpp文件中定义构造函数,而不仅仅是析构函数。

如果Outer构造函数失败,它将需要销毁m_ptr,这需要了解class Inner的定义。