加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – unique_ptr pimpl和不完整类型

发布时间:2020-12-16 10:12:24 所属栏目:百科 来源:网络整理
导读:这不是 std::unique_ptr with an incomplete type won’t compile的欺骗. 请考虑以下代码: #include memorystruct X{ X(); ~X(); struct Impl; std::unique_ptrImpl up_;};struct Impl {}; // fully visible hereX::X() : up_{nullptr}{}X::~X() = default;
这不是 std::unique_ptr with an incomplete type won’t compile的欺骗.

请考虑以下代码:

#include <memory>

struct X
{
    X();
    ~X();    

    struct Impl; 
    std::unique_ptr<Impl> up_;
};

struct Impl {}; // fully visible here

X::X() : up_{nullptr}{}
X::~X() = default;

int main()
{
    X x;
}

Live on Coliru

gcc / clang都吐了一个错误,说Impl不完整.但是,在Impl完全可见之后,我为X提供了一个默认的析构函数,因此IMO代码应该编译.为什么不呢?现在出乎意料的是:如果我让Impl成为一个内部类,即定义

struct X::Impl{};

相反,然后the code compiles,即使没有提供析构函数.为什么会这样?我们不应该提供这样的默认析构函数,至少根据第一行中提到的链接?

解决方法

你有两个不同的结构名为Impl.

struct X
{
    struct Impl; // Here you declare X::Impl
    std::unique_ptr<Impl> up_;  // Here you create a pointer to a X::Impl
};

struct Impl {};  // Here you declare and define ::Impl

...

int main()
{
    X x;  // Here X::Impl is still incomplete
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读