Question

I am trying to understand how to give back memory if one class creates another class.

I have

 Clas A;

Then another class that allocate memory for Class A:

class B{
    private:
        A* data;
    public:
        // Allocating new memory
        B (){
                  A* data =  new A();

        //giving memory back
        ~B(){
                   delete data; };
};

And when I execute the code in main function it just crashes. What am doing wrong? I am a bit lost here. Thanks.

Was it helpful?

Solution

Get rid of the redundant A* in the constructor. What this does is create a new, local variable with the same name as your class member. So the real B::data never gets anything assigned to it, and when you try to delete it, things blow up. To add insult to injury, the new A() you assign to the local data will be leaked (well; it would be leaked if the program didn't crash).

class B{
    private:
        A* data;
    public:
        // Allocating new memory
        B (){
           data =  new A();
        }

        //giving memory back
        ~B(){
           delete data;
        }
};

That solves the immediate problem, but as juanchopanza noted in the comments, you will still run into problems if you try to copy this object.

OTHER TIPS

Here's the RAII / Rule of Zero route (assuming your compiler supports C++11)

class A {};

class B {
private:
    std::unique_ptr<A> data;

public:
    B() : data(new A) {
    }
};

The RAII handle in this case a unique_ptr will take care of deallocation for you. Implementing it this means the compiler defined copy constructor, copy assignment operator, move constructor, move assignment operator and destructor will all work fine right out the box.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top