在 C++ 中测试 void 指针删除之前
我在 C++ 中有一个数组:
Player ** playerArray;
它在它所在类的构造函数中初始化。
在析构函数中我有:
delete playerArray;
除了通过 Valgrind 测试程序时,它说有一些调用删除了 void 指针:
operator delete(void*)
我想在调用delete之前测试playerArray是否为void指针以避免此错误。
有谁知道该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许您的意思是
删除[]playerArray
。如果指针是数组而不是单个实例,则需要[]
。Perhaps you meant
delete [] playerArray
. You need the[]
if the pointer is an array, not a single instance.以下是删除运算符的定义方式。
“operator delete”采用“void *”,因为指向任何对象的指针都可以转换为“void *”。
请注意,void 是不完整类型,因此不允许删除 void * 即
如果playerarray是指向玩家数组的指针,您很可能希望以不同的方式进行操作。
delete pplayer
不会执行您想要的操作。Here's how operator delete is defined.
'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
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.我认为 valgrind 警告的是,删除是在这样的上下文中发生的:
虽然转换很好,因为你碰巧知道 void 指针实际上是那种类型,所以你仍然在做一些可疑的事情,因为您正在删除 void 指针,而不是类型化指针。如果 SomeClass 是 POD,那可能没问题,但如果它有一些关键工作必须在其析构函数中完成,则该析构函数永远不会被调用。
I think what valgrind is warning about is that the delete is occuring in the context of something like this:
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.