Test for void pointer in C++ before deleting

夙愿已清 提交于 2019-11-27 08:01:44

问题


I have an array in C++:

Player ** playerArray;

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

In the destructor I have:

delete playerArray;

except when testing the program through Valgrind it says that there are some calls to delete to a void pointer:

 operator delete(void*)

I want to test whether the playerArray is a void pointer before calling delete to avoid this error.

Does anyone know how to do this?


回答1:


Perhaps you meant delete [] playerArray. You need the [] if the pointer is an array, not a single instance.




回答2:


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.




回答3:


I think what valgrind is warning about is that the delete is occuring in the context of something like this:

int foo(void *mydata){
{
    SomeClass some_value = static_cast<SomeClass> mydata;
    some_value.dosomething();
    // now we're done with it
    delete mydata;
}

although the cast is fine, since you happen to know that the void pointer is actually that type, you're still doing something fishy, because you're deleting the void pointer, rather than the typed pointer. If SomeClass is POD, that's probably ok, but if it has some critical work it must do in its destructor, that destructor never gets called.



来源:https://stackoverflow.com/questions/3844374/test-for-void-pointer-in-c-before-deleting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!