如何删除void指针? [英] How to delete void pointer?

查看:489
本文介绍了如何删除void指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中删除这样的对象时有什么问题吗?

Is there anything wrong when deleting an object like this in C++?

MyCls* c = new MyCls();
void* p = (void*)c;
delete (MyCls*)p;

推荐答案

此内容合法.

强制转换回MyCls*是至关重要的.否则,您将调用未定义的行为-不会调用MyCls析构函数,并且也可能会出现其他问题(例如崩溃).您必须回退到正确的类型.

The cast back to MyCls* is critical. Without that, you will invoke undefined behavior--the MyCls destructor will not be called, and other problems may arise as well (such as a crash). You must cast back to the correct type.

还请注意,如果涉及多个继承并且使用多个强制类型转换,则这可能会很复杂.您的演员阵容必须在任一方向上匹配".

Also note that this can be complicated if multiple inheritance is involved and multiple casts are used. Your casts must "match" in either direction.

如果代码的结构使得您在销毁时不知道类型,请为每个可删除对象提供一个带有虚拟析构函数的通用基类.然后在调用delete之前将其强制转换回基类.

If your code is structured such that you won't know the type at the time of destruction, give each deletable object a common base class with a virtual destructor. Then cast back to the base class before delete is called.

这篇关于如何删除void指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆