Boost logo

Boost Users :

Subject: Re: [Boost-users] shared_ptr and circular dependency
From: Lars Viklund (zao_at_[hidden])
Date: 2012-03-30 17:46:13

On Fri, Mar 30, 2012 at 08:14:18PM +0000, Christopher Pisz wrote:
> Emil Dotchevski <emildotchevski <at>> writes:
> > You could use weak_ptr to break shared_ptr cycles.
> >
> > Emil Dotchevski
> > Reverge Studios, Inc.
> >
> >
> >From boost docs:
> Q. Can an object create a weak_ptr to itself in its constructor?
> A. No. A weak_ptr can only be created from a shared_ptr, and at object
> construction time no shared_ptr to the object exists yet.
> This is the problem I cannot seem to easily overcome in both the case of the
> shared and weak ptr. It seems to work with a raw this pointer, but then I
> cannot achieve my goal.

If you have control over the places where the objects of the type are
created, you might want to have two-phase initialization with a factory
function to protect you from misuse.

That is, something like (ignoring access and all):

  struct B
    void init(weak_ptr<B> p) { self = p; }
    weak_ptr<B> self;

  struct D : B

  shared_ptr<D> MakeD(..)
    shared_ptr<D> ret = make_shared<D>(..);
    return ret;

Lars Viklund | zao_at_[hidden]

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at