使用<T>带有前向清除的unique_ptr导致 C2027 和 C2338
Use unique_ptr<T> with forward declearation leads to C2027 and C2338
这是一个简单的代码版本:
//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
的定义。
相关文章:
- 为什么 std::unique 不调用 std::sort?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 生成"unique"矩阵
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 我对 std::unique(算法)C++有问题
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++中的指针否定 (!ptr == NULL)
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误