2

I have a question. I was playing with enable_shared_from_this and noticed a strange thing. This example works fine:

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

struct Test : enable_shared_from_this<Test>
{
};

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

But when I change struct to class it stops compiling!

The error says:

/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);

Does anyone have a clue why it is so?

dyp
  • 38,334
  • 13
  • 112
  • 177
Jack
  • 21
  • 1

2 Answers2

4

This might be a (minor) defect in the C++ Standard!

The difference between struct and class in the example is the default accessibility of base classes:

struct Test : enable_shared_from_this<Test>

derives publicly from enable_shared_from_this;

class Test : enable_shared_from_this<Test>

derives privately from enable_shared_from_this;

However, I cannot find any (normative) requirement in the Standard that requires an accessible enable_shared_from_this base class for constructing a shared_ptr.

[util.smartptr.enab]/6 about enable_shared_from_this::shared_from_this() requires:

enable_shared_from_this<T> shall be an accessible base class of T.

But I do not see where the Standard mandates using that function or any other explicit requirement about the accessibility of the enable_shared_from_this base class.

The possible implementation given in [util.smartptr.enab]/10-11 does require an accessible base class; so I think the normative parts are intended to require accessibility.

dyp
  • 38,334
  • 13
  • 112
  • 177
1

Add public before enable_shared_from_this

class Test : public enable_shared_from_this<Test>
{



};
rayryeng
  • 102,964
  • 22
  • 184
  • 193
Vlad Gorodetsky
  • 101
  • 1
  • 4