C++ 使用D_ptr实现析构函数
我尝试在Qt小部件中实现使用D_ptr的PIMPL方法 下面的代码是我实现的C++ 使用D_ptr实现析构函数,c++,qt,pimpl-idiom,C++,Qt,Pimpl Idiom,我尝试在Qt小部件中实现使用D_ptr的PIMPL方法 下面的代码是我实现的 class GuiCentralHandler : public QWidget { Q_OBJECT public: GuiCentralHandler (QWidget *parent = 0); ~GuiCentralHandler (); protected: GuiCentralHandlerPrivate * const d_ptr; private: //class m
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;
}
而我的私人私家侦探是
class GuiCentralHandlerPrivate
{
Q_DECLARE_PUBLIC(GuiCentralHandlerPrivate )
public:
GuiCentralHandlerPrivate (GuiCentralHandler *parent);
protected:
GuiCentralHandler * const q_ptr;
};
GuiCentralHandlerPrivate ::GuiCentralHandlerPrivate (GuiCentralHandler *parent)
: q_ptr(parent)
{
}
但是当我调用GuiCentralHandler::~GuiCentralHandler()
它正在崩溃。如何从主窗口小部件中删除dptr
或d_func。
请指出此实现的错误所在。您应该传递指向的指针,而不是指针的地址:
delete d_ptr;
而不是:
delete &d_ptr;
,您可以找到有关d指针的信息您正在将父对象设置为
guicentralhanderprivate
,然后显式删除它。这会删除对象两次,从而导致崩溃。请尝试替换delete&d\u ptr代码>带有删除d_ptr代码>@jaac感谢您的回复。我也试过了。当我在GuiCentralHandler::~GuiCentralHandler()中删除析构函数delete,但它没有调用私有类csGuiCentralModuleHandlerPrivate::~csGuiCentralModuleHandlerPrivate(){qDebug()的析构函数时@安德烈谢谢安德烈,是的,我也试过了。@Jaa-c,guicentralhanderprivate
它不是从QObject
派生的,所以它的构造函数中的parent
在Qt方面不是parent
对象,不会被自动删除