如何安全地删除多个指针 [英] How to safely delete multiple pointers

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

问题描述

我有一些代码使用了很多指向同一个地址的指针。
给出一个等效的简单例子:

I have got some code which uses a lot of pointers pointing to the same address. Given a equivalent simple example:

int *p =  new int(1);
int *q = p;
int *r = q;

delete r; r = NULL; // ok
// delete q; q = NULL; // NOT ok
// delete p; p = NULL; // NOT ok

如何安全地删除它而不删除多个?
如果我有很多对象,其指针都指向同一个地址,这是特别困难的。

How to safely delete it without multiple delete? This is especially difficult if I have a lot of objects which having pointers all pointing to the same address.

推荐答案

没有求助于管理指针的答案是,你应该知道是否根据分配的位置删除指针。

The answer, without resorting to managed pointers, is that you should know whether or not to delete a pointer based on where it was allocated.

你的例子是一种设计,但在现实世界的应用程序中,负责分配内存的对象将负责破坏它。接收已经初始化的指针并存储一段时间的方法和函数不删除那些指针;

Your example is kind of contrived, but in a real world application, the object responsible for allocating memory would be responsible for destroying it. Methods and functions which receive already initialized pointers and store them for a time do not delete those pointers; that responsibility lies with whatever object originally allocated the memory.

请记住,您对 new 的调用应该由您对 delete 的调用。每次分配内存时,您都知道必须写出平衡代码(通常是析构函数)来释放内存。

Just remember that your calls to new should be balanced by your calls to delete. Every time you allocate memory, you know you have to write balancing code (often a destructor) to deallocate that memory.

这篇关于如何安全地删除多个指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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