在我的例子中,当你想删除一个对象时,我对使用 delete
和 destroy
感到困惑,例如:
app.h
#include "taskBarIcon.h"
class myApp: public wxApp{
public:
// ....
private:
CTaskBarIcon *m_pTaskbar; // = NULL
};
app.cpp
int myApp::OnExit() {
if (m_pTaskbar != NULL) {
delete m_pTaskbar; // <-- The problem here
m_pTaskbar = NULL;
}
return 0;
}
int myApp::OnRun() {
mainFrm *_mainFrm = mainFrm::getInstance(); // The main window
_mainFrm->Show(false);
m_pTaskbar = new CTaskBarIcon(_mainFrm);
m_pTaskbar->SetIcon(wxIcon("appIcon"), _mainFrm->GetTitle());
return wxApp::OnRun();
}
CTaskBarIcon.cpp
void CTaskBarIcon::rightButton_Click(wxTaskBarIconEvent & event) {
PopupMenu(CreatePopupMenu());
}
void CTaskBarIcon::popupMenu_showWindow(wxCommandEvent & event) {
m_pHandler->Iconize(false); // 'm_pHandler' is the main window
m_pHandler->Show();
m_pHandler->Raise();
this->Destroy();
}
void CTaskBarIcon::popupMenu_showAbout(wxCommandEvent & event) {
aboutFrm aboutWindow(m_pHandler, "About");
aboutWindow.ShowModal();
aboutWindow.Raise();
}
void CTaskBarIcon::popupMenu_exit(wxCommandEvent & event) {
m_pHandler->Close(true);
this->Destroy();
}
前面的代码导致程序退出时出现运行错误,原因是删除了成员变量m_pTaskbar
:
// app.cpp
int myApp::OnExit() {
if (m_pTaskbar != NULL) {
delete m_pTaskbar; // <-- The problem here
m_pTaskbar = NULL;
}
return 0;
}
但请注意,我在 CTaskBarIcon.cpp
代码的不同地方使用了 this->Destroy()
。
delete
和 destroy
有什么区别,它们做的是同一件事吗?
最佳答案
WXWidgets 对其wiki 有解释:
The wxCloseEvent handler should only call
wxWindow::Destroy()
to delete the window, and not use thedelete
operator. This is because for some window classes, wxWidgets delays actual deletion of the window until all events have been processed, since otherwise there is the danger that events will be sent to a non-existent window.
核心保留了一个打开的窗口列表,它将决定何时对这些对象实际调用 delete
。客户不应该自己直接调用它。
关于c++ - wxWidgets中的 'delete'和 'destroy'有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52188016/