使用unique_ptr进行前向声明?

Zyx*_*000 62 c++ destructor forward-declaration unique-ptr

我发现std::unique_ptr在下面的代码中结合使用前向声明类很有用.它编译并与GCC一起工作,但整个事情似乎有点奇怪,我想知道这是否是标准行为(即标准要求)?因为B声明时B不是完整的类型unique_ptr.

A.hpp

#include <memory>

class B;

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

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.
Run Code Online (Sandbox Code Playgroud)

我怀疑这与析构函数有关(因此需要调用析构函数unique_ptr<B>)是在特定的编译单元(A.cpp)中定义的.

Jam*_*nze 61

这显然是合法的.规则是,除非另有说明,否则用于在标准库中实例化模板的类型必须完整.在unique_ptr§20.7.1/ 5 的情况下,"[...] unique_ptr的模板参数T可能是不完整的类型."

指针上有一些需要完整类型的操作; 特别是当对象实际被破坏时(至少使用默认删除器).在您的示例中,例如,如果 A::~A()是内联的,这可能会导致问题.(请注意,如果您没有自己声明析构函数,它将是内联的.这部分地违背了使用目的std::unique_ptr.)

  • “这部分抵消了使用std :: unique_ptr的目的”是什么意思?如果不声明dtor,类实例是否不会自动删除其成员? (3认同)
  • 因此,不可能创建一个具有与“unique_ptr”类似功能的自定义模板类,因为 C++ 标准为“unique_ptr”定义了自定义规则以使其工作? (3认同)
  • 哇,这是析构函数引起的问题。一旦我在 .cpp 文件中明确定义它,一切就消失了。 (3认同)