Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is delete necessary in a destructor?

I have the following code and I'm wondering if that delete b is necessary here ? Will my operating system automatically clear that area of memory allocated ?

class A
{
    B *b;

    A()
    {
        b = new B();
    }

    ~A() 
    {
        delete b;
    }
};

Many thanks.

like image 425
daisy Avatar asked Jun 28 '11 06:06

daisy


1 Answers

Yes, you have to delete every object created with new that you own. In this very case it looks like class A owns that very instance of class B and is responsible for calling delete.

You'll be much better off using a smart pointer for managing class B instance lifetime. Also note that you have to either implement or prohibit assignment operator and copy constructor in class A to prevent shallow copying the object which will cause you much trouble.

like image 129
sharptooth Avatar answered Sep 27 '22 16:09

sharptooth