How to free a void pointer.
struct vStruct {
void *vPtr;
struct vStruct *next;
};
struct vStruct sObj;
struct vStruct *sObjNew = sObj;
delete sObjNew-&
You should not delete a void
pointer. delete
works for specific types (such that compiler knows, which destructor should be called - as stated in error message).
If you want to hold unspecified type in your structure, you have to wrap it somehow.
class DataWrapper
{
public:
virtual void * GetData() = 0;
virtual ~DataWrapper()
{
}
};
class MyDataWrapper
{
protected:
MyData * data;
public:
MyDataWrapper(MyData * newData)
{
data = newData;
}
void * GetData()
{
return data;
}
~MyDataWrapper()
{
delete data;
}
};
struct vStruct
{
MyDataWrapper * vPtr;
struct vStruct *next;
~vStruct()
{
if (vPtr != null)
delete vPtr;
}
};
vStruct sObj;
sObj.vPtr = new MyDataWrapper(new MyData());
// When sObj gets deleted, MyDataWrapper is
// deleted too (thanks to the ~vStruct) and
// in effect, the allocated data is deleted too.
Note, that it's a simple example, it can be written more aesthetically.