C ++删除指向指针的指针 [英] C++ deleting a pointer to a pointer

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

问题描述

所以我有一个指向指针数组的指针.如果我这样删除它:

So I have a pointer to an array of pointers. If I delete it like this:

delete [] PointerToPointers;

是否还会删除所有指向指针的指针?如果不是,是否必须遍历所有指针并将其删除,还是有更简单的方法呢?对于这个问题,我的google-fu似乎没有给我任何好的答案.

Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answers to this question.

(是的,我知道我需要使用向量.这是学校中的赶上C ++"类型分配之一.)

(And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.)

推荐答案

是的,您必须遍历指针,并逐个删除.

Yes you have to loop over the pointers, deleting individually.

原因:如果其他代码在您的数组中有指向对象的指针,该怎么办? C ++编译器不知道这是否正确,因此必须明确.

Reason: What if other code had pointers to the objects in your array? The C++ compiler doesn't know if that's true or not, so you have to be explicit.

以更简便的方式",有两个建议:(1)为此目的创建一个子例程,这样至少您不必多次编写代码. (2)使用智能指针"设计范例,其中包含带有引用计数器的对象数组,然后当不再由任何代码引用对象时,将删除对象.

For an "easier way," two suggestions: (1) Make a subroutine for this purpose so at least you won't have to write the code more than once. (2) Use the "smart pointer" design paradigm where you hold an array of objects with reference-counters, then the objects are deleted when the objects are no longer referenced by any code.

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

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