使用unique_ptr转发声明? [英] Forward declaration with unique_ptr?

查看:164
本文介绍了使用unique_ptr转发声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have found it useful to use forward declaration of classes in combination with std::unique_ptr as in the code below. It compiles and works with GCC, but the whole thing seem kind of strange, and I wonder if this is standard behaviour (i.e. required by the standard)? Since B isn't a complete type when I declare the unique_ptr.

#include <memory>

class B;

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



A.cpp



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.

我怀疑这与析构函数有关(因此需要调用<$

I suspect this has to do with the destructor (and therefore the need to call the destructor of unique_ptr<B>) is defined in a specific compilation unit (A.cpp).

推荐答案

这是明确合法的。规则是,在标准库中用于实例化
模板的类型必须完成,除非指定
,否则。在 unique_ptr 的情况下,§20.7.1/ 5说[...]
模板参数T的unique_ptr可能是一个不完整的类型。 ;

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.”

指针上有一些操作需要一个完整的
类型;特别是当对象实际上将被破坏时(在
处,最小值为缺省的删除者)。在你的例子中,例如,如果
A ::〜A()是内联的,这可能会导致问题。 (注意,如果
不自己声明析构函数,它将是inline的。其中
部分地违反了使用 std :: unique_ptr 。)

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.)

这篇关于使用unique_ptr转发声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆