What is boost's shared_ptr(shared_ptr const & r, T * p) used for?

后端 未结 6 1236
孤街浪徒
孤街浪徒 2021-02-01 04:28

boost::shared_ptr has an unusual constructor

template shared_ptr(shared_ptr const & r, T * p);

and I a

6条回答
  •  南笙
    南笙 (楼主)
    2021-02-01 05:02

    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 instance p 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. The make_shared factory function presented later in this document can also be implemented using only the public interface of shared_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 stores p and shares ownership with r.

    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 of r is destroyed. --end note.]

    [Note: This constructor allows creation of an empty shared_ptr instance with a non-NULL stored pointer. --end note.]

提交回复
热议问题