Boost logo

Boost :

From: Oleg Fedtchenko (BoostOleg_at_[hidden])
Date: 2004-10-28 03:44:10


> Peter Dimov wrote:
>
> This is a bit harder.
>
> class A
> {
> private:
> WORD m_wData;
>
> private:
> A();
>
> public:
> static shared_ptr<A> CreateA() { return shared_ptr<A>(new A); }
>
> friend shared_ptr<WORD> GetData( shared_ptr<A> this_ )
> {
> return shared_ptr<WORD>(
> &this_->m_wData,
> boost::bind( &shared_ptr<A>::reset, this_ )
> );
> }
> };
>
> int main()
> {
> shared_ptr<A> pa = A::CreateA();
> shared_ptr<WORD> pw = GetData(pa);
> pa.reset();
> std::cout << "*pw: " << *pw << '\n';
> }

Parameter this_ in the function (above)

     friend shared_ptr<WORD> GetData( shared_ptr<A> this_ )

is an owner of a data member this_->m_wData.

But the owner may be not an immediate
class-container-of-the-member or its derivative but any
arbitrary class like this:

class A
{
public:
    WORD m_wData;
};

class B
{
public:
    A a;

    friend shared_ptr<WORD> GetData( shared_ptr<B> this_ )
    {
        return shared_ptr<WORD>(
            &this_->a.m_wData,
            boost::bind( &shared_ptr<A>::reset, this_ )
        );
    }
};

In this case we must create overridden functions for every
owner type to correctly specify pointer to a member.
And what about when A::m_wData is private?

Don't you think this is the better variant:

    template<class Z>
    shared_ptr<WORD> A::GetData( shared_ptr<Z> owner )
    {
        return shared_ptr<WORD>(
            &m_wData,
            boost::bind( &shared_ptr<Z>::reset, owner )
        );
    }

Oleg Fedtchenko

The proposed smart pointer member_ptr is described at
http://boostoleg.narod.ru/member_ptr.html

thread entry
http://lists.boost.org/MailArchives/boost/msg72943.php


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