使用D_ptr实现析构函数

using D_ptr implementation destructor

本文关键字:实现 析构函数 ptr 使用      更新时间:2023-10-16

我尝试在Qt小部件中使用D_ptr实现PIMPL方法。

下面的代码是我实现的。

class GuiCentralHandler : public QWidget
{
    Q_OBJECT
public:
    GuiCentralHandler (QWidget *parent = 0);
    ~GuiCentralHandler ();
protected:
    GuiCentralHandlerPrivate * const d_ptr;
private: //class methods
    Q_DECLARE_PRIVATE(GuiCentralHandler )
};
GuiCentralHandler ::GuiCentralHandler (QWidget *parent)
    :QWidget(parent),d_ptr(new GuiCentralHandlerPrivate (this))
{
}
GuiCentralHandler ::~GuiCentralHandler ()
{
    Q_D(GuiCentralHandler );
    delete &d_ptr;
}

和我的私有d_ptr是

class GuiCentralHandlerPrivate 
{
    Q_DECLARE_PUBLIC(GuiCentralHandlerPrivate )
public:
     GuiCentralHandlerPrivate (GuiCentralHandler *parent);
protected:
    GuiCentralHandler * const q_ptr;
};
GuiCentralHandlerPrivate ::GuiCentralHandlerPrivate (GuiCentralHandler *parent)
    : q_ptr(parent)
{
}

但是当我调用GuiCentralHandler ::~GuiCentralHandler ()的析构函数时它正在崩溃。我如何从主要小部件中删除d_ptr或d_func。请指出我在这个实现中哪里出错了

应该传递一个指针给delete操作符,而不是指针的地址:

delete d_ptr;

代替:

delete &d_ptr;

在这里,您可以找到有关d-pointer

的信息