Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the standard mandate enable_shared_from_this is to be inherited publicly? Why?

It's common to inherit from enable_shared_from_this just to be able to return shared_ptr's from member functions as the primary intention, with no intention of exposing enable_shared_from_this API in the derived class.

Since to make use of enable_shared_from_this one must do so through public inheritance (does the standard mandates this? what's the rationale?), this can't be achieved and enable_shared_from_this API is forced into derived class public API.

Inherenting enable_shared_from_this privately and making shared_ptr a friend class do work on clang coupled with libc++, but doesn't work with stdlibc++.

Since private enable_shared_from_this + friend shared_ptr (or protected inheritance) seems to cover this use case, shouldn't it be sufficient by the standard for fitting as a solution for the "shared from this" problem?

like image 277
pepper_chico Avatar asked Jul 03 '16 01:07

pepper_chico


People also ask

Why use enable_ shared_ from_ this?

Using enable_shared_from_this essentially allows the code to works properly in cases it would not have otherwise. By using that, it allows to find internal data used to maintain reference count.

What is enable_ shared_ from_ this?

Defined in header <memory> template< class T > class enable_shared_from_this; (since C++11) std::enable_shared_from_this allows an object t that is currently managed by a std::shared_ptr named pt to safely generate additional std::shared_ptr instances pt1, pt2, ... that all share ownership of t with pt .


1 Answers

Since private enable_shared_from_this + friend shared_ptr seems to cover this use case, shouldn't it be sufficient by the standard?

No. The standard permits implementations wide latitude with how they implement things. The constructor of shared_ptr<T> that adopts an object may defer the shared-from-this stuff to some helper function or other object. For maximum irony, it could defer to a base class of shared_ptr<T> ;)

As such, enable_shared_from_this must be accessible by any code in order for the shared_ptr constructor to work.

like image 96
Nicol Bolas Avatar answered Nov 06 '22 09:11

Nicol Bolas