This is the mail archive of the mailing list for the GCC project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: enable_shared_from_this fails at runtime when inherited privately

On Thu, 29 Aug 2019 at 10:15, Christian Schneider
<> wrote:
> Hello,
> I just discovered, that, when using enable_shared_from_this and
> inheriting it privately, this fails at runtime.
> I made a small example:
> #include <memory>
> #include <boost/shared_ptr.hpp>
> #include <boost/make_shared.hpp>
> #include <boost/enable_shared_from_this.hpp>
> #ifndef prefix
> #define prefix std
> #endif
> class foo:
>      prefix::enable_shared_from_this<foo>
> {
> public:
>      prefix::shared_ptr<foo> get_sptr()
>      {
>          return shared_from_this();
>      }
> };
> int main()
> {
>      auto a = prefix::make_shared<foo>();
>      auto b = a->get_sptr();
>      return 0;
> }
> This compiles fine, but throws a weak_ptr exception at runtime.
> I'm aware, that the implementation requires, that
> enable_shared_from_this needs to be publicly inherited, but as a first
> time user, I had to find this out the hard way, as documentations (I
> use, ie. don't mention it, probably because it's not a
> requirement of the standard.

It definitely is a requirement of the standard. The new wording we
added via
says that the base's weak_ptr is only initialized when the base class
is "unambiguous and accessible". It doesn't say that an ambiguous or
inaccessible base class makes the program ill-formed, so we're not
allowed to reject such a program.

> On the other hand, if you compile the code with additional
> -Dprefix=boost (and needed boost stuff installed, of course), it gives a
> compiler error (
> gcc: 'boost::enable_shared_from_this<foo>' is an inaccessible base of 'foo';
> clang: error: cannot cast 'boost::shared_ptr<foo>::element_type' (aka
> 'foo') to its private base class 'boost::enable_shared_from_this<foo>')

That seems like a bug in Boost.

> I'm think, it would be helpful, if the std implemantions also would fail
> at compile time already, and wanted to ask if this would be
> possible/feasible.

No, that would not conform to the standard.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]