在 Qt 中控件同时使用智能指针和父子关系,会有二次删除风险吗?

14次阅读

共计 939 个字符,预计需要花费 3 分钟才能阅读完成。

比如一个像下面这样定义的 QDialog 窗体:

#ifndef PLAYDIALOG_H
#define PLAYDIALOG_H

#include 
#include 
#include 

class QPushButton;

class PlayDialog : public QDialog
{
    Q_OBJECT
public:
    explicit PlayDialog(QWidget* parent = nullptr);

private:
    QVBoxLayout* m_layout;

    QPushButton* m_button1;
    std::shared_ptr m_button2;
    QSharedPointer m_button3;
};

#endif // PLAYDIALOG_H

#include "playdialog.h"

#include 
#include 
#include 
#include 
#include 

PlayDialog::PlayDialog(QWidget* parent) : QDialog(parent), m_layout(new QVBoxLayout(this))
{m_button1 = new QPushButton("BUTTON1", this);
    m_button2 = std::make_shared("BUTTON2", this);
    m_button3 = QSharedPointer::create("BUTTON3", this);

    m_layout->addWidget(m_button1);
    m_layout->addWidget(m_button2.get());
    m_layout->addWidget(m_button3.get());

    setLayout(m_layout);
}

其中的 QPushButton 都设置了 QDialog 窗体为父控件,m_button2m_button3 分别用 C++ 原生和 Qt 的智能指针进行了包装。如果这个时候关掉父窗体,因为父子级关系三个按钮都会被释放,但是受智能指针管理的 m_button2m_button3按理说也会被释放,这种时候会存在二次删除风险吗?是不是在 Qt 中不应该用智能指针管理设置了父子级关系的 QWidget 控件?还是说 Qt 封装过的 QSharedPointer 可以放心使用?

正文完
 0