Boost logo

Boost Users :

From: gast128 (gast128_at_[hidden])
Date: 2008-06-23 06:16:56

> First of all, I like to use the concept of a "master" shared_ptr. That is, I
attempt to design my architectures so that there is one shared_ptr which
persists for the lifetime of the object being pointed to; other shared_ptrs
are transient, in that they persist for a shorter period of time (typically
which a particular piece of work is being performed). To pursue the metaphor,
the "master" shared_ptr holds its object in existence. It is the pointer which
(when reset) ultimately causes the object to be deleted.
> Using this concept, my parent object holds the master shared_ptr of its
child. (Typically there are multiple children and their master shared_ptrs are
stored in a vector.) The child holds a weak_ptr to its parent. In my work,
typically both parent and child inherit from enable_shared_from_this.
> The "trick" is to treat the parent-child relationship seriously. Since child
objects do not exist except in the context of a parent, it is logical to
create a function member of the parent which is responsible for creating the
child and establishing linkages. (Or, if this needs to occur elsewhere, the
child is constructed by some other [third-party] object's member function
which creates the child and links the child and parent together.) It should
not be necessary to construct the child in the parent's constructor, nor
should it be necessary to establish linkages with the parent in the child's
constructor. The problems you are concerned about need not exist. As long as
the construction of the child and its linkage to its parent occur in a single
member-function, it should not be necessary for either the parent's or the
child's constructor to be responsible for establishing the linkage.

what you ultimately describe is a 2 phase construction. If the invariant of
your class is that the parent is only valid if it also has its required
children, only after the second phase the invariant of the parent can be

Although 2 phase construction is regarded as a bad thing, I think it can not
be circumvented in every situation (e.g. 2 phase construction allows
polymorphic behavior and sometimes you need to make first A then B and then
link). During construction and destruction (or in general during change)
objects may be in an inconsistent state and dependent objects should be
careful then.

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