C++ 指针数组:删除还是删除 []? [英] C++ Array of pointers: delete or delete []?

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

问题描述

考虑以下代码:

class Foo
{
    Monster* monsters[6];

    Foo()
    {
        for (int i = 0; i < 6; i++)
        {
            monsters[i] = new Monster();
        }
    }

    virtual ~Foo();
}

正确的析构函数是什么?

What is the correct destructor?

这个:

Foo::~Foo()
{
    delete [] monsters;
}

或者这个:

Foo::~Foo()
{
    for (int i = 0; i < 6; i++)
    {
        delete monsters[i];
    }
}

我目前有最上面的构造函数,一切正常,但当然我看不到它是否碰巧泄漏......

I currently have the uppermost constructor and everything is working okey, but of course I cannot see if it happens to be leaking...

就我个人而言,考虑到我在做什么,我认为第二个版本更合乎逻辑.无论如何,这样做的正确"方法是什么?

Personally, I think the second version is much more logical considering what I am doing. Anyway, what is the "proper" way to do this?

推荐答案

delete[] Monsters;

不正确,因为monsters 不是指向动态分配数组的指针,它 是一个指针数组.作为类成员,类实例销毁时会自动销毁.

Is incorrect because monsters isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.

您的另一个实现是正确的,因为数组中的指针确实指向动态分配的 Monster 对象.

Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster objects.

请注意,使用当前的内存分配策略,您可能希望声明自己的复制构造函数和复制赋值运算符,以便无意的复制不会导致双重删除.(如果您想防止复制,您可以将它们声明为私有,而不实际实现它们.)

Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)

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

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