如何在不知道其类型的情况下删除结构?

时间:2013-10-20 20:26:50

标签: c++ structure

这是我的代码:

struct WndProcStatus {
    WNDPROC OrgWndProc;
};

struct ButtonWndProcStatus {
    WNDPROC OrgWndProc;
    bool bIsPressed;
    bool bIsFocused;
    bool bIsDefault;
    bool bIsDisabled;
    bool bDrawFocusRect;
    bool bMouseOver;
    bool bShowAccel;
};

struct EditBoxWndProcStatus {
    WNDPROC OrgWndProc;
    bool bIsFocused;
    bool bIsDisabled;
    bool bMouseOver;
    bool bTextSelected;
};

在我的程序中,我将有一个指向ButtonWndProcStatus结构或EditBoxWndProcStatus结构的指针,但我不知道它是哪一个。

我可以将指针强制转换为WndProcStatus,然后使用delete命令从内存中删除结构吗?

指针是使用LONG ptr = (LONG)new ButtonWndProcStatus()LONG ptr = (LONG)new EditWndProcStatus()创建的。

3 个答案:

答案 0 :(得分:1)

没有

  

delete-expression ::: opt 删除 cast-expression < / p>      

在第一个替代(删除对象)中,如果是静态类型的   要删除的对象不同于其动态类型,静态   type应该是对象的动态类型的基类   删除和静态类型应具有虚拟析构函数或   行为未定义[5.3.5 / 3]

delete的操作数应与分配的类型相同(除非基本/派生情况)

答案 1 :(得分:1)

不,你不能这样做。只有在使用继承并且为结构/类提供虚拟析构函数时它才有效:

struct WndProcStatus
{
    virtual ~WndProcStatus() = default;

    WNDPROC OrgWndProc;
};

struct ButtonWndProcStatus
    : public WndProcStatus // derive, this also inherits OrgWndProc
{
    bool bIsPressed;
    bool bIsFocused;
    bool bIsDefault;
    bool bIsDisabled;
    bool bDrawFocusRect;
    bool bMouseOver;
    bool bShowAccel;
};

现在通过指针删除应该是安全的。此外,您可以轻松编写

WndProcStatus* p = new ButtonWndProcStatus; // look ma, no cast!
delete p; // this is now safe

答案 2 :(得分:-1)

使用operator delete时,未指定已删除对象的类型。所以我没有看到问题,因为据我所知,你没有任何结构的继承。