QMessageBox出现野指针
在使用QMessageBox的时候,会有非堵塞的需求。通常会用到如下代码。
#include <QMessageBox>
QMessageBox m_messageBox = new QMessageBox(QMessageBox::Information, tr("demo"), tr("Wild pointer"));
m_messageBox->setModal(false);
m_messageBox->setAttribute(Qt::WA_DeleteOnClose);
m_messageBox->show();
在析构的过程中会出现异常。
if (nullptr != m_messageBox)
{
delete m_messageBox;
m_messageBox = nullptr;
}
异常如下:
原因:
void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on = true)
Sets the attribute attribute on this widget if on is true; otherwise clears the attribute.
在关闭时对资源进行了释放,但没有对指针赋值为nullptr。之后对指针进行操作会出现访问野指针的异常。
因此,如果要对非堵塞的QMessageBox进行管理。需要做如下调整。
m_messageBox->setAttribute(Qt::WA_DeleteOnClose,false);