Array of structs and new / delete

后端 未结 8 920
没有蜡笔的小新
没有蜡笔的小新 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:21

    There are a few, related, questions here:

    1. According to the code you posted, the array itself is not allocated on the heap unless the struct is, so you don't need to delete[] the array. If you created the array with new[] you would have to delete[] it.
    2. The code posted doesn't say how the objects being pointed to from the array are allocated. If you allocate those objects on the stack you must not delete them (then again, this is highly unlikely because your pointers will become invalid when the objects they point to fall out of scope). If you allocated them on the heap (with new) then you must delete them when they fall out of scope.
    3. As others have already suggested, life is much easier if you use a container -- especially an STL container -- and smart pointers -- which for now means pointers out of Boost.

提交回复
热议问题