Boost logo

Boost Users :

From: Martin Ecker (martin.ecker_at_[hidden])
Date: 2003-08-22 11:57:04


I've been thinking of switching one of my projects to
use boost::smart_ptr and I'm currently investigating
this option a bit.

In my project there are a lot of cases where an object
acts as factory/parent object to create other child
These child objects must keep the parent object
alive as long as one of them still exists. Or in other
words, even if the client does not hold a pointer to
the parent object anymore, the parent must continue
to exist as long as there is still a child object.
Also the child objects sometimes need to have
access to the parent object that created them.
Therefore, I thought I'd have them hold a shared_ptr
to the parent object.

So the situation looks something like this, where
both Parent and Child objects are only allocated on the
heap and should only be passed around as shared_ptr.

class Parent
    boost::shared_ptr<Child> CreateChild() const
        boost::shared_ptr<Child> child(new Child(this));
        return child;

class Child
    friend class Parent;

    Child(const boost::shared_ptr<Parent> parent)
        : m_parent(parent)

    boost::shared_ptr<Parent> m_parent;

As far as I understand it I can't do new Child(this) because
Child expects a shared_ptr, so I'd have to derive Parent from
However, in my project there are a number of classes in a rather
complicated class hierarchy to which the above pattern applies
and I'd thus like to avoid having to (multiply) derive them from
Is there another, possibly better way of achieving what I
want to do (keep the parent alive as long as there are still
child objects) that I haven't discovered yet? Or do I really
have to derive all these classes from enable_shared_from_this?
Do I have to derive each class in a class hierarchy from
enable_shared_from_this, if each of them needs to give
out a shared_ptr-managed this pointer?

Thanks for any help,

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