gpt4 book ai didi

c++ - 使用具有前向声明的 unique_ptr 导致 C2027 和 C2338

转载 作者:搜寻专家 更新时间:2023-10-31 02:03:06 31 4
gpt4 key购买 nike

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

//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), 在析构函数中自动删除(默认析构函数), 但是为什么我用的时候还需要包含内部类的实现(Inner.h) ?

最佳答案

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

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

关于c++ - 使用具有前向声明的 unique_ptr<T> 导致 C2027 和 C2338,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56019908/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com