使用enable_shared_from_this的类vs结构

时间:2014-09-30 14:57:19

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

我有一个问题。我正在玩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: error:
‘std::enable_shared_from_this’ is an inaccessible base of ‘Test’
    __enable_shared_from_this_helper(_M_refcount, __p, __p);

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

2 个答案:

答案 0 :(得分:4)

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

示例中structclass之间的差异是基类的默认可访问性:

struct Test : enable_shared_from_this<Test>

enable_shared_from_this

中公开
class Test : enable_shared_from_this<Test>

enable_shared_from_this

中私下导出

但是,我在标准中找不到任何(规范性)要求,要求构建 a enable_shared_from_this的基本shared_ptr基类。

[util.smartptr.enab] / 6约enable_shared_from_this::shared_from_this()要求:

  

enable_shared_from_this<T>应为T的可访问基类。

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

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

答案 1 :(得分:1)

public

之前添加enable_shared_from_this
class Test : public enable_shared_from_this<Test>
{



};