Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2004-10-06 05:50:45


Oleg Fedtchenko wrote:
> To Peter Dimov
>
> Hi, Peter
>
> Could you, please, tell if is there a smart pointer template to a
> class data-member.
> I failed to find an appropriate pointer among five ones existing in
> the boost.
>
> I need it for the two tasks appended.

No, none of the existing pointers address the problem directly, although
shared_ptr can be persuaded to do what you want.

> Task 2)
>
> class DocActiveX
> {
> protected:
> Tree* m_pTree;
>
> public:
> ~DocActiveX(){ if(m_pTree) delete m_pTree;}
> bool Load( const char* lpszPath);
> Tree* Parse(){ return m_pTree;}
> };

That's the easy part.

class DocActiveX
{
private:

    shared_ptr<Tree> m_pTree;

public:

    bool Load( const char* lpszPath );
    shared_ptr<Tree> Parse() { return m_pTree; }
};

> Task 1)
>
> class A
> {
> public:
> A(){ m_wData = 0;}
> WORD* GetData(){ return &m_wData}
> A* CreateA( int nOffset){ return new A;}
>
> protected:
> WORD m_wData;
> };

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';
}


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