Opened 14 years ago

Last modified 13 years ago

#2911 new Feature Requests

shared_from_this free function

Reported by: fhess Owned by: Frank Mori Hess
Milestone: To Be Determined Component: smart_ptr
Version: Boost 1.38.0 Severity: Problem
Keywords: Cc: jwakely.boost@…

Description

Attached is an implementation of a free shared_from_this function, plus a non-template enable_shared_from_this_base class which can only be used with the free shared_from_this function. The free function will also work with the usual enable_shared_from_this template. It is implemented on top of the existing enable_shared_from_this class, and so requires no modification of the existing smart_ptr code.

This scheme has the advantage of simplicity, since the "curiously recurring template pattern" is not needed. It also "just works" if you have a class hierarchy that looks like "X is derived from Y is derived from enable_shared_from_this_base" and want to use shared_from_this with both X and Y.

I've only tried it with gcc 4.3.

Attachments (1)

shared_from_this.hpp (956 bytes ) - added by fhess 14 years ago.
free boost::shared_from_this template function

Download all attachments as: .zip

Change History (3)

by fhess, 14 years ago

Attachment: shared_from_this.hpp added

free boost::shared_from_this template function

comment:1 by Jonathan Wakely <jwakely.boost@…>, 13 years ago

Cc: jwakely.boost@… added

This idea is interesting, but I don't like the name because there is no this pointer in the context of a non-member function. Maybe I'm wrong, but I regard the "this" in shared_from_this as referring to this. How about shared_from instead?

X* p = ...;
shared_ptr<X> sp = shared_from(p);

It also seems odd to have a class called enable_shared_from_this_base which has a base class called enable_shared_from_this! I understand the reasons, but it seems backwards at first glance.

Renaming the free function to shared_from means your new class could be renamed enable_shared_from. Users who only want to use the free function can derive their class X from enable_shared_from (and don't need to care that calling p->enable_shared_from_this() returns a shared_ptr<enable_shared_from> not a shared_ptr<X>) while users who want to use either the free function or the existing member function can continue to derive from enable_shared_from_this<X>.

comment:2 by Peter Dimov, 13 years ago

Milestone: Boost 1.39.0To Be Determined
Owner: changed from Peter Dimov to Frank Mori Hess
Note: See TracTickets for help on using tickets.