Is delete necessary in a destructor?

2020-04-03 07:00发布

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.

9条回答
贪生不怕死
2楼-- · 2020-04-03 07:55

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.

查看更多
我只想做你的唯一
3楼-- · 2020-04-03 07:56

Resource management is more than just deallocating memory. Yes, most platforms will make any memory you allocate when the process ends, and memory is cheap enough that maybe you won't notice for a while. But what about the file b is holding open, or the mutex it will unlock in its destructor? Well before you run out of memory, you can encounter issues from letting your objects live past their usefullness.

查看更多
家丑人穷心不美
4楼-- · 2020-04-03 07:58

It will clear the area only when the process ends, but the area will remain allocated all the time until then, which means memory leak.

查看更多
登录 后发表回答