当多个指针指向一个对象时删除它? [英] Deleting an object when multiple pointers are pointing to it?

查看:77
本文介绍了当多个指针指向一个对象时删除它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人告诉我,如果我有多个指针指向同一个对象,我无法正常删除它(使用 delete 关键字).相反,我被告知需要将指针设置为 NULL 或 0.

I've been told that when if I have multiple pointers pointing to the same object, I cannot delete it normally (using the delete keyword). Instead, I've been told that I need to set the pointers to NULL or 0.

鉴于我有:

ClassA* object = new ClassA();
ClassA* pointer1 = object;
ClassA* pointer2 = object;

那么要delete pointer1pointer2,我需要做以下事情吗?

So to delete pointer1 and pointer2, do I need to do the following?

pointer1 = 0;
pointer2 = 0:

一旦我将它设置为 NULL,我还需要使用关键字 delete 吗?或者只是将其设置为 0 就足够了?

Once I've set it to NULL, do I still need to use the keyword delete? Or is just setting it to 0 good enough?

推荐答案

每当你new一个对象时,你需要delete它,释放内存

Whenever you new an object, you need to delete it, free'ing the memory

ClassA* object = new ClassA();

delete object; // Free's the memory you allocated.

将指针设置为 NULL 的目的是停止取消引用无效

The point of setting your pointers to NULL is to stop dereferencing pointers that are invalid

object = NULL;

这样做是为了在尝试取消引用之前执行测试:

This is done so that tests can be performed before attempting a dereference:

if(object != NULL)
{
  object->SomeMethod(); // We can assume it's safe to use the pointer.
}

还要注意,您可以从指向它的任何指针中删除内存.

Also note that you can delete the memory from any pointer that points to it.

ClassA* object = new ClassA();
ClassA* pointer1 = object;
ClassA* pointer2 = object;

delete pointer1; 

object, pointer1, and pointer2 现在指向已经释放的内存,除非重新定义,否则都应该设置为NULL.

object, pointer1, and pointer2 now all point to memory that has already been released, and unless they will be redefined, they should all be set to NULL.

这篇关于当多个指针指向一个对象时删除它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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