【问题标题】:Class vs struct with enable_shared_from_this具有 enable_shared_from_this 的类与结构
【发布时间】:2014-09-30 14:57:19
【问题描述】:

我有一个问题。我在玩enable_shared_from_this 并注意到一件奇怪的事情。这个例子很好用:

#include <iostream>
#include <memory>
using namespace std;

struct Test : enable_shared_from_this<Test>
{
};

int main() {
    shared_ptr<Test> ptr(new Test);
    return 0;
}

但是当我将struct 更改为class 时,它会停止编译!

错误提示:

/usr/include/c++/4.8/bits/shared_ptr_base.h:772:58:错误: ‘std::enable_shared_from_this’ 是 ‘Test’ 的一个不可访问的基础 __enable_shared_from_this_helper(_M_refcount, __p, __p);

有人知道为什么会这样吗?

【问题讨论】:

  • struct 的默认继承是public,而class 的默认继承是private
  • 对。默认继承就是答案。谢谢!

标签: c++ c++11 shared-ptr private-inheritance


【解决方案1】:

这可能是 C++ 标准中的一个(次要)缺陷!

示例中structclass的区别在于基类的默认可访问性:

struct Test : enable_shared_from_this<Test>

enable_shared_from_this 派生公开

class Test : enable_shared_from_this<Test>

enable_shared_from_this私下派生

但是,我在标准中找不到任何需要可访问的enable_shared_from_this 基类来构造shared_ptr

[util.smartptr.enab]/6 关于enable_shared_from_this::shared_from_this() 需要:

enable_shared_from_this&lt;T&gt; 应该是T 的可访问基类。

但我没有看到标准要求在哪里使用该函数或任何其他关于 enable_shared_from_this 基类可访问性的明确要求。

[util.smartptr.enab]/10-11 中给出的可能实现确实需要一个可访问的基类;所以我认为规范部分旨在要求可访问性。

【讨论】:

    【解决方案2】:

    enable_shared_from_this之前添加public

    class Test : public enable_shared_from_this<Test>
    {
    
    
    
    };
    

    【讨论】:

      猜你喜欢
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多