Array of structs and new / delete

2020-02-28 09:10发布

I have a struct like this:

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?

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

8条回答
做自己的国王
2楼-- · 2020-02-28 09:54

C++ isn't my strong suit, but I'm pretty sure you'd be leaking the memory if you set the pointer to NULL.

EDIT: The memory being leaked would be the memory being pointed to by the pointer in the array.

查看更多
再贱就再见
3楼-- · 2020-02-28 09:56

Just to be clear: you refer to calling "delete[]". I think you mean delete.

I mention this because C++ has two separate operators, operator delete and operator delete[]. The latter is used for deleting arrays of objects allocated with operator new[], and does not apply in this case. You have an array of pointers to objects, which you must have initialised with repeated calls to operator new rather than a single call to operator new[].

All I'm really trying to say is: your use of delete[] is confusing and ambiguous; change it to delete.

查看更多
登录 后发表回答