这是我的代码:
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/