跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

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

发表于

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

#ifndef PLAYDIALOG_H
#define PLAYDIALOG_H

#include <memory>
#include <QVBoxLayout>
#include <QDialog>

class QPushButton;

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

private:
    QVBoxLayout* m_layout;

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

#endif // PLAYDIALOG_H

#include "playdialog.h"

#include <memory>
#include <QDialog>
#include <QLayout>
#include <QPushButton>
#include <QVBoxLayout>

PlayDialog::PlayDialog(QWidget* parent) : QDialog(parent), m_layout(new QVBoxLayout(this))
{

    m_button1 = new QPushButton("BUTTON1", this);
    m_button2 = std::make_shared<QPushButton>("BUTTON2", this);
    m_button3 = QSharedPointer<QPushButton>::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 可以放心使用?

Featured Replies

No posts to show

创建帐户或登录来提出意见

Account

导航

搜索

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.