结构的数组和新/删除 [英] Array of structs and new / delete

查看:139
本文介绍了结构的数组和新/删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的结构:

class Items 
{
private:
    struct item
    {
        unsigned int a, b, c;
    };
    item* items[MAX_ITEMS];
}

说我想'删除'一个项目,像这样:

Say I wanted to 'delete' an item, like so:

items[5] = NULL;

和我上同一地点以后创建一个新项目:

And I created a new item on that same spot later:

items[5] = new item;

我还需要调用删除[] 来打扫一下吗?或将不是这个需要,因为数组的边界项目[] 是在编译之前已知的?

Would I still need to call delete[] to clean this up? Or won't this be needed since bounds of array items[] are known before compiling?

时设置该指针为NULL有效或我应该调用删除吗?

Is setting that pointer to NULL valid or should I be calling delete there?

推荐答案

您需要调用将其设置为NULL之前删除。 (将其设置为NULL不是必需的,它只是帮助减少错误,如果你不小心尝试取消引用指针删除后)。

You need to call delete before setting it to NULL. (Setting it to NULL isn't required, it just helps reduce bugs if you accidentally try to dereference the pointer after deleting it.)

请记住,每次使用时间,你将需要使用删除后来对同一指针。切勿使用一个没有其他。

Remember that every time you use new, you will need to use delete later on the same pointer. Never use one without the other.

此外,新[] 删除[] 一起去以同样的方式,但你千万不要混用新[] 删除删除[] 。在你的榜样,因为你创造与对象(而不是新[] 这将创建对象的数组)您必须删除与对象删除(而不是删除[] )。

Also, new [] and delete [] go together in the same way, but you should never mix new [] with delete or new with delete []. In your example, since you created the object with new (rather than new [] which would create an array of objects) you must delete the object with delete (rather than delete []).

这篇关于结构的数组和新/删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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