Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-04-07 07:07:17


From: "Christian Kreibich" <kreibich_at_[hidden]>
> Hi all,
>
>
> my question is related to your smart pointer package which I've been
> using for a long time now, although the core of my problem is just one
> of circular dependencies, and I'm kind of embarrassed because the answer
> must be pretty obvious.
>
> I usually use your smart pointers like this:
>
> class A
> {
> public:
> typedef boost::shared_ptr<A> ptr;
> // ...
> };
>
> so that afterwards I can conveniently access the smart pointers as
>
> A::ptr aptr(new A(...));
>
> My problem now appears when I have two classes that use each other's
> smart pointers, for example as in here:
>
> class A
> {
> public:
> typedef boost::shared_ptr<A> ptr;
> virtual B::ptr createB();
> };
>
> class B
> {
> public:
> typedef boost::shared_ptr<B> ptr;
> virtual void setA(A::ptr aptr);
> private:
> A::ptr _aptr;
> };
>
> You get the idea. Is there a way to keep using my typedef style within
> the classes and resolve the circular dependencies? On a more general
> note, what is the suggested idiom for handling this situation?

This problem is not shared_ptr-specific; it usually comes up with containers
and iterators. The solution (within the current language) is to define the
types outside the class:

class A;
typedef boost::shared_ptr<A> A_ptr;
class A
{
public:
    typedef A_ptr ptr;
};

You can still keep the A::ptr notation, but now you can break circular
dependencies by using the global A_ptr alias.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk