Boost logo

Boost Users :

Subject: Re: [Boost-users] shared_ptr design question
From: Lars Viklund (zao_at_[hidden])
Date: 2011-09-20 11:46:35


On Tue, Sep 20, 2011 at 05:43:49PM +0300, Igor R wrote:
> > shared_ptr also has an aliasing copy constructor, where you can give it an
> > arbitrary pointer.  So, you might make a shared_ptr that points at a struct
> > and a shared_ptr that points at a member of the same struct, but they both
> > share the same reference count and deleter.
>
> Could you elaborate a bit?
>
> struct inner
> {
> //...
> };
> struct outer
> {
> inner inner_;
> };
>
> Do you mean that one can make shared_ptr<inner> from shared_ptr<outer>?

Very much that, yes.

shared_ptr<outer> o = make_shared<outer>();
shared_ptr<inner> i = shared_ptr<inner>(o, &o->i);

The aliasing ctor holds the second pointer argument, while using the
refcounting of the first argument.

There's no restriction that the pointer has to be to inside the object
at all, but it tends to be the common use case.

-- 
Lars Viklund | zao_at_[hidden]

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net