boost::shared_ptr
has an unusual constructor
template shared_ptr(shared_ptr const & r, T * p);
and I a
To expand on leiz's and piotr's answers, this description of shared_ptr<>
'aliasing' is from a WG21 paper, "Improving shared_ptr for C++0x, Revision 2":
III. Aliasing Support
Advanced users often require the ability to create a
shared_ptr
instancep
that shares ownership with another (master)shared_ptr
q
but points to an object that is not a base of*q
.*p
may be a member or an element of*q
, for example. This section proposes an additional constructor that can be used for this purpose.An interesting side effect of this increase of expressive power is that now the
*_pointer_cast
functions can be implemented in user code. Themake_shared
factory function presented later in this document can also be implemented using only the public interface ofshared_ptr
via the aliasing constructor.Impact:
This feature extends the interface of
shared_ptr
in a backward-compatible way that increases its expressive power and is therefore strongly recommended to be added to the C++0x standard. It introduces no source- and binary compatibility issues.Proposed text:
Add to
shared_ptr
[util.smartptr.shared] the following constructor:template
shared_ptr( shared_ptr const & r, T * p ); Add the following to [util.smartptr.shared.const]:
template
shared_ptr( shared_ptr const & r, T * p ); Effects: Constructs a
shared_ptr
instance that storesp
and shares ownership withr
.Postconditions:
get() == p && use_count() == r.use_count()
.Throws: nothing.
[Note: To avoid the possibility of a dangling pointer, the user of this constructor must ensure that
p
remains valid at least until the ownership group ofr
is destroyed. --end note.][Note: This constructor allows creation of an empty
shared_ptr
instance with a non-NULL stored pointer. --end note.]