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

How do I delete a stucture without knowing its type?

本文关键字:情况下 删除 结构 类型 不知道      更新时间:2023-10-16

这是我的代码:

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() 创建的。

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

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

No.

删除表达式: ::选择删除转换表达式

在第一个备选方案(删除对象)中,如果静态类型 要删除的对象不同于其动态类型,即静态 类型应是要成为的对象的动态类型的基类 已删除,静态类型应具有虚拟析构函数或 行为未定义 [5.3.5/3]

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