如何释放空指针。
struct vStruct {
void *vPtr;
struct vStruct *next;
};
struct vStruct sObj;
struct vStruct *sObjNew = sObj;
delete sObjNew->vPtr; -----------> Is this correct way to delete void pointer
delete sObjNew;
显示错误运算符“删除”,应用于具有未定义行为的 void* 参数,并且很可能不会调用对象的析构函数。
最佳答案
您不能删除
void 指针。为什么?因为:
'delete', applied to
void*
argument has undefined behavior, and most likely does not invoke the object's destructor.
您的编译器如何知道指针对象的类型?因此要调用哪个析构函数? (尽管它可能可以确定要释放多少内存,具体取决于分配机制。)
不要存储 void*
— 而是使用“真正的”指针类型。如果您需要“隐藏”真实类型,请考虑使用多态性 而不是过时的 C 实践。
关于c++ - 释放空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16809998/