【发布时间】:2012-11-05 01:32:13
【问题描述】:
我发现将类的前向声明与std::unique_ptr 结合使用很有用,如下面的代码所示。它编译并与 GCC 一起工作,但整个事情看起来有点奇怪,我想知道这是否是标准行为(即标准所要求的)?因为当我声明 unique_ptr 时 B 不是一个完整的类型。
A.hpp
#include <memory>
class B;
class A {
std::unique_ptr<B> myptr;
// B::~B() can't be seen from here
public:
~A();
};
A.cpp
#include "B.hpp"
//B.hpp has to be included, otherwise it doesn't work.
A::~A() = default; // without this line, it won't compile
// however, any destructor definiton will do.
我怀疑这与析构函数有关(因此需要调用 unique_ptr<B> 的析构函数)是在特定的编译单元 (A.cpp) 中定义的。
【问题讨论】:
标签: c++ destructor forward-declaration unique-ptr