Array of structs and new / delete

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

    As Kluge pointed out, you'd leak the object at index 5 like that. But this one really sounds like you shouldn't do this manually but use a container class inside Item. If you don't actually need to store these item objects as pointers, use std::vector instead of that array of MAX_ITEMS pointers. You can always insert or erase vector elements in the middle as well if you need to.

    In case you need to store the objects as pointers (usually if struct item is actually polymorphic, unlike in your example), you can use boost::ptr_vector from Boost.PtrContainer instead.

    Example:

    class Items {
    private:
        struct item {
            unsigned int a, b, c;
        };
        std::vector items;
    }
    
    if (items.size() > 5) // (just to ensure there is an element at that position)
        items.erase(items.begin() + 5); // no need to use operator delete at all
    

提交回复
热议问题