Array of structs and new / delete

后端 未结 8 867
没有蜡笔的小新
没有蜡笔的小新 2021-01-02 18:47

I have a struct like this:

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

8条回答
  •  醉梦人生
    2021-01-02 19:29

    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 []).

提交回复
热议问题