使用 D_ptr 实现析构函数

using D_ptr implementation destructor

我尝试在 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。 请指出我在这个实现中哪里出了问题。

您应该传递指向 operator delete 的指针而不是指针的地址:

delete d_ptr;

而不是:

delete &d_ptr;

Here,你可以找到关于d指针的信息