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

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

问题描述

Cosider以下code:

Cosider the following code:

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?

推荐答案

删除[]怪物;

不正确,因为怪物不是指向一个动态分配的数组,它的的指针数组。作为一类成员当类实例被销毁,将被自动销毁。

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.

您其它的实现是正确的为数组中的指针就指向动态分配怪物的对象。

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

请注意,以你目前的内存分配策略,你可能想声明自己的拷贝构造函数和拷贝赋值运算符,这样无意的复制不会导致双删除。 (如果您想prevent复制,你可以声明它们为私有,实际上没有实现它们。)

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天全站免登陆