Zyx*_*000 62 c++ destructor forward-declaration unique-ptr
我发现std::unique_ptr在下面的代码中结合使用前向声明类很有用.它编译并与GCC一起工作,但整个事情似乎有点奇怪,我想知道这是否是标准行为(即标准要求)?因为B声明时B不是完整的类型unique_ptr.
#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)
#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.)