Deleting an object with a member which contains a pointer back to the object
I have an object A that has a member1 which is another object B. That
member1 contains a member2 which is a pointer back to object A. When I try
to delete object A, I get a segfault, which I'm guessing is because it's
deleting object B which then tries to delete object A again.
Here's a real quick example that follows my code similarly, so you can get
an idea:
    class B;
    class A
    {
        B member1;
        A() : member1(this)
        { }
        ~A()
        { }
    };
    class B
    {
        A* const member2;
        B(A* const myA) : member2(myA)
        { }
        ~A()
        { }
    };
    int main()
    {
        A* objectToDelete = new A();
        delete A;
    }
Is there a better way to arrange this? Preferably I would like to keep the
objects pointing to each other because of the way things are set up for
the program.
 
No comments:
Post a Comment