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

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

最佳答案

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

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

关于c++ - 如何在不知道结构类型的情况下删除结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19482464/

相关文章:

c++ - 如何在调用 addData(...) 函数时增加结构的大小,以便我可以保存更多数据

json - 使用 jq 和 bash 显示 json 各级的结构

c++ - 运行 UNIX 应用程序的堆栈跟踪

c++ - 使用河豚在大端和小端之间发送 dgram 消息

c++ - 展开路径中包含环境变量的文件名

c++ - 只需在 Qt 中更新标签

c - 在结构中如何存储值?

data-structures - 在Prolog中创建队列结构

c++ - 包含 unordered_map 作为成员的结构的 sizeof()

c++ - 将矩形转换为梯形以获得透视效果