使用<T>带有前向清除的unique_ptr导致 C2027 和 C2338

Use unique_ptr<T> with forward declearation leads to C2027 and C2338

本文关键字:ptr unique 导致 C2338 C2027 gt lt 使用 清除      更新时间:2023-10-16

这是一个简单的代码版本:

//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")

我已阅读 std::unique_ptr 需要知道 T 的完整定义吗? 我知道如果我在"main.cpp"中包含"Inner.h",问题就可以解决。但是为什么?

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

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

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

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