在析构函数中是否需要删除? [英] Is delete necessary in a destructor?

查看:166
本文介绍了在析构函数中是否需要删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,我想知道在这里是否需要delete b吗? 我的操作系统会自动清除分配的内存区域吗?

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;
    }
};

非常感谢.

推荐答案

是的,您必须delete用自己拥有的new 创建的每个对象.在这种情况下,class A似乎拥有class B的那个实例,并负责调用delete.

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.

使用智能指针管理class B实例生存期会更好.还要注意,您必须在class A中实现或禁止赋值运算符和复制构造函数,以防止浅复制对象,这会给您带来很多麻烦.

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.

这篇关于在析构函数中是否需要删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆