Array of structs and new / delete

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

    Say I wanted to 'delete' an item, like so:

    items[5] = NULL;

    I know little Visual Basic, but that smells like a Visual Basic programming idiom, since "Set a = None" (or Null, I'm not sure) would delete the object pointed by a (or rather decrement its reference count, for COM objects).


    As somebody else noted, you should use either:

    delete items[5];
    items[5] = newContent;
    

    or:

    delete items[5];
    items[5] = NULL;
    

    After delete[5], the only possible use of the pointer stored in items[5] is causing you trouble. What's worse is that it might happen to work at the beginning, and start failing only when you allocate something else over the space previously used by *items[5]. Those are the causes which make C/C++ programming "interesting", i.e. really annoying (even for who likes C like me).

    Writing just delete items[5]; saves what can be an useless write, but that's a premature optimization.

提交回复
热议问题