删除指针数组 - 我这样做对吗? [英] Deleting an Array of Pointers - Am I doing it right?

查看:202
本文介绍了删除指针数组 - 我这样做对吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得有点愚蠢作出关于指针的缺失问题,但我需要确保我删除以正确的方式为我正在经历我的程序的调试过程。

I feel a little stupid for making a question about the deletion of pointers but I need to make sure I'm deleting in the correct way as I'm currently going through the debugging process of my program.

基本上我有这是在我的头文件中定义一个指针数组数如下:

Basically I have a few arrays of pointers which are defined in my header file as follows:

AsteroidView *_asteroidView[16];

在for循环然后我初始化它们:

In a for loop I then initialise them:

for(int i = 0; i < 16; i++)  
{  
      _asteroidView[i] = new AsteroidView();  
} 

好了,到目前为止好,一切工作正常。
当我最终需要在我用这个code析构函数删除这些:

Ok, so far so good, everything works fine. When I eventually need to delete these in the destructor I use this code:

for(int i = 0; i < 16; i++)  
{  
        delete _asteroidView[i];  
}

这是所有我需要做什么?我觉得是这样,但我担心会内存泄漏。

Is this all I need to do? I feel like it is, but I'm worried about getting memory leaks.

出于兴趣......
也有很大的点数组之间的差异与对象数组比较的对象?

Out of interest... Is there much of a difference between an Array of Points to Objects compared with an Array of Objects?

推荐答案

这是正确的。但是,您可能要考虑使用 Boost.PointerContainer ,并节省您的手动费尽口舌资源管理的麻烦:

This is correct. However, you may want to consider using Boost.PointerContainer, and save you hassle the hassle of manual resource management:

boost::ptr_vector<AsteroidView> _asteroidView;
for(int i = 0; i < 16; i++)
{
    _asteroidView.push_back(new AsteroidView());
}

您不必管理缺失,容器是否适合您。这种技术被称为 RAII ,你应该了解,如果你想用C ++有乐趣: )

You do not have to manage the deletion, the container does that for you. This technique is called RAII, and you should learn about it if you want to have fun using C++ :)

关于您的编辑:有几个不同,但我想最重要的是这些:

About your edit: There are several difference, but I guess the most important are these:


  1. 指针数组可以包含不同类型的对象,如果这些是阵列类型的子类。

  2. 对象的数组不需要任何删除,当阵列被破坏的所有对象都毁灭了。

这篇关于删除指针数组 - 我这样做对吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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