Test for void pointer in C++ before deleting

前端 未结 3 588
南旧
南旧 2020-12-11 20:18

I have an array in C++:

Player ** playerArray;

which is initialized in the constructor of the class it is in.

In the destructor I

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 21:04

    Here's how operator delete is defined.

    void operator delete(void*) throw();
    void operator delete[](void*) throw();
    

    'operator delete' takes a 'void *' since a pointer to any object can be converted to 'void *'.

    Note that a void is an incomplete type and hence it is not allowed to delete a void * i.e

    char *p = new char;
    void *pv = p;
    delete pv;            // not allowed
    

    Footnote 78: This implies that an object cannot be deleted using a pointer of type void* because void is not an object type.

    In the case where playerarray is a pointer to an array of Players, you most likely want to do it differently. delete pplayer does not do what you want it to.

提交回复
热议问题