freeing a void pointer

前端 未结 3 570
故里飘歌
故里飘歌 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条回答
  •  时光说笑
    2021-01-28 15:07

    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.

提交回复
热议问题