Boost logo

Boost Users :

From: Michael Brinkmann (yg-boost-users_at_[hidden])
Date: 2002-12-17 09:44:51


Hello,

given the following code which uses shared_ptrs, I'm getting a double-free
onto an object of type A:

------------------------------------------------------
#include <boost/shared_ptr.hpp>
#include <list>
#include <iostream>

class A {
public:
    A(void){}
    void makeSomething(void);
    void makeSomethingOther(void)
    {
        std::cout << "A" << std::endl;
    }
};

typedef boost::shared_ptr<A> APtr;
class B
{
public:
    B(const APtr& a)
        : mA(a)
        {}
    void makeSomething(void)
    {
        std::cout << "B" << std::endl;
        mA->makeSomethingOther();
    }
private:
    APtr mA;
};

void A::makeSomething(void)
{
    B b(this); // here I want to hand over the "A"
shared pointer to "B", but I have only my "this" at hand.
    std::cout << "A" << std::endl;
    b.makeSomething();
}

int main(void)
{
    APtr a(new A);
    a->makeSomething();
}

------------------------------------------------------
(please don't ask me about why I'm doing it in that way, the code is
stripped down from a much
bigger program)

I understand that the problem results from the accesss to "this" in the
commented line.
Is there an elegant way to get the shared_ptr pointing to "this" from
"this", which would
be the solution to the fault?
Or do I have to store a shared_ptr member variable referencing "this" in the
class A
which is set by a A::method from outside of A to reference it? (not very
beautiful)

Sorry if this is a FAQ, but I didn't find a solution on news.gmane.org

kind regards
Michael


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net