在析构函数中是否需要删除? [英] Is delete necessary in a destructor?
问题描述
我有以下代码,我想知道在这里是否需要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屋!