前向声明?

我发现,如下面的代码所示,将类的前向声明与 std::unique_ptr结合使用是非常有用的。它与 GCC 一起编译和工作,但是整个事情看起来有点奇怪,我想知道这是否是标准行为(即标准所要求的) ?因为当我声明 unique_ptr时 B 不是一个完整的类型。

高血压

#include <memory>


class B;


class A {
std::unique_ptr<B> myptr;
// B::~B() can't be seen from here
public:
~A();
};

心肺复苏术

#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)中定义的。

51407 次浏览

It's explicitly legal. The rule is that the types used to instantiate a template in the standard library must be complete, unless otherwise specified. In the case of unique_ptr, §20.7.1/5 says “[...] The template parameter T of unique_ptr may be an incomplete type.”

There are certain operations on the pointer which require a complete type; in particular, when the object will actually be destructed (at least with the default deleter). In your example, for example, if A::~A() were inline, this might cause problems. (Note that if you don't declare the destructor yourself, it will be inline. Which partially defeats the purpose of using std::unique_ptr.)