Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-08-23 09:38:39


Martin Ecker wrote:
[...]
> 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
> {
> public:
> boost::shared_ptr<Child> CreateChild() const
> {
> boost::shared_ptr<Child> child(new Child(this));
> return child;
> }
> };

The most straightforward way is to make CreateChild a free function (or a
static member of Parent, or a static member of Child, depending on the
design):

shared_ptr<Child> CreateChild(shared_ptr<Parent> const & px)
{
    shared_ptr<Child> child(new Child(px));
    return child;
}

as described in

http://www.boost.org/libs/smart_ptr/sp_techniques.html#from_raw

If you need CreateChild to be virtual, enable_shared_from_this is the only
option.


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