freeing a void pointer

前端 未结 3 610
故里飘歌
故里飘歌 2021-01-28 14:47

How to free a void pointer.

struct vStruct {
    void *vPtr;
    struct vStruct *next;
};

struct vStruct sObj;
struct vStruct *sObjNew = sObj;

delete sObjNew-&         


        
3条回答
  •  萌比男神i
    2021-01-28 15:08

    You do not delete a void pointer. Why? Because:

    'delete', applied to void* argument has undefined behavior, and most likely does not invoke the object's destructor.

    How would your compiler know which type the pointee object has? And therefore which destructor to call? (Though it can probably determine how much memory to free, depending on the allocation mechanism.)

    Do not store a void* — use a "real" pointer type instead. If you need to "hide" the true type, consider employing polymorphism instead of antiquated C practices.

提交回复
热议问题