Array of structs and new / delete

后端 未结 8 866
没有蜡笔的小新
没有蜡笔的小新 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 []).

    0 讨论(0)
  • 2021-01-02 19:33

    Setting items[5] to NULL doesn't delete the memory associated with the item, it simply sets the pointer to that item to NULL, therefore the memory is leaked.

    You can delete the item by calling:

    delete items[5];
    

    Since C++ has not automatic garbage collection, you need to delete any memory you no longer need.

    0 讨论(0)
提交回复
热议问题