I want to have the following class structure:
#include <tr1/memory>
class Interface;
class Impl;
class Impl
{
public:
Impl( std::tr1::weak_ptr< Interface > interface );
private:
std::tr1::weak_ptr< Interface > interface_;
};
class Interface
{
public:
Interface() { impl_ = new Impl( this ); }
private:
std::tr1::shared_ptr< Impl > impl_;
};
Impl::Impl( std::tr1::weak_ptr< Interface > interface )
: interface_(interface)
{}
The code doesn’t work since a weak_ptr can only be constructed from a shared_ptr. I can’t construct a shared_ptr of this in the ctor since it would destroy the object when leaving the ctor.
The interface will be held as a shared_ptr by the caller. The Implementation needs to be shared_ptr since its lifetime is longer than the Interface lifetime.
Is there an elegant way to establish this relationship?
I solved it by removing the need to use shared_ptr< Interface > from the Impl.
The underlying problem was that the Interface is a Node in a directed acyclic graph. Each node knows its parents and children, so implementing a Node::addChild( shared_ptr< Node > child ) is impossible, since the node cannot be added as a weak_ptr to the child’s parents.
One way is to use intrusive_ptr, but I solved it by using a static Node::link( shared_ptr< Node > parent, shared_ptr< Node > child ) method for now.
I might end up using intrusive_ptr later if I need to do a enable_shared_from_this-like operation.