Boost logo

Boost :

From: Johan Nilsson (r.johan.nilsson_at_[hidden])
Date: 2007-03-01 07:17:49


Michael Anderson wrote:

[snip]

>
>
> For example I want this to work... where ptr<Bar> is some kind of
> smart (or otherwise) pointer to a bar object.
>
> {
> ptr<Bar> barPtr;
> {
> ptr<Foo> fooPtr(new Foo);
> barPtr = fooPtr->bar;
> //A
> }
> barPtr->doSomething(); //B
> //C
> }

Something similar is possible if Bar is polymorphic, see below. I'm leaving
out includes and the "boost::" namespace references, but it should give you
the basic idea:

--- Bar.h ---

struct Bar
{
    virtual void Baz() = 0;
};

--- Foo.h ---

struct Foo
    : enable_shared_from_this<Foo>
{
    Foo();

    shared_ptr<Bar> GetBar();

private:
    shared_ptr<Bar> pBar_;
};

---- Foo.cpp ----

namespace {

struct BarImpl
: Bar
{
    void Baz()
    { }
};

struct BarDelegatorWithFooRef
    : Bar
{
    BarDelegatorWithFooRef(shared_ptr<Foo> pFoo, shared_ptr<Bar> pBar)
        : pFoo_(pFoo)
        , pBar_(pBar)
    {}

    void Baz()
    { pBar_->Baz(); }

private:
    shared_ptr<Foo> pFoo_;
    shared_ptr<Bar> pBar_;
};

} // anonymous namespace

Foo::Foo()
    : pBar_(new BarImpl)
{}

shared_ptr<Bar> Foo::GetBar()
{
    return shared_ptr<Bar>(new BarDelegatorWithFooRef(shared_from_this(),
pBar_));
}

---------------

The following should then work as you wished:

{
   shared_ptr<Bar> barPtr;
   {
     shared_ptr<Foo> fooPtr(new Foo);
     barPtr = fooPtr->GetBar();
   }
   barPtr->doSomething();
}

Beware of typos!

/ Johan


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