相关疑难解决方法(0)

使用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)中定义的.

c++ destructor forward-declaration unique-ptr

62
推荐指数
1
解决办法
3万
查看次数

标签 统计

c++ ×1

destructor ×1

forward-declaration ×1

unique-ptr ×1