Question

I've to use Singleton pattern for widget in my app. So I've made implementation for this.

testwidget.h

class TestWidget;

class TstWidgetHolder
{
static TestWidget* wobj;
public:
    static const TestWidget* instance();
    static void setParent(QWidget*);
};

class TestWidget : public QWidget
{
   Q_OBJECT
   friend class TstWidgetHolder;
private:
   Ui::TestWidget ui;

   explicit TestWidget(QWidget *parent = 0);
   ~TestWidget();
 };

testwidget.cpp

TestWidget::TestWidget(QWidget *parent) :
    QWidget(parent)
{
    ui.setupUi(this);
}

TestWidget::~TestWidget() 
{}

TestWidget* TstWidgetHolder::wobj = NULL;
void TstWidgetHolder::setParent(QWidget* obj)
{
   static TestWidget tst(obj);
   TstWidgetHolder::wobj = &tst;
}
const TestWidget* TstWidgetHolder::instance()
{
   return wobj;
}

As simple as this. Then is main program I'm setting up parent to this singleton.

TstWidgetHolder::setParent(this);

And there the real problem comes. When main widget closes, application crashes.

According to debugger, the destructor of singleton widget is being called twice. And that's of course is the cause of crash.

What's the problem? Is it bug in Qt or mine logic?

HERE SOURCE CODE

Was it helpful?

Solution

When you make TstWidgetHolder::setParent(this) you are delegating ownership (in other words, responsability to destruct) of the TestWidget instance to this. So, right before the object pointed to by this is destructed, it tries to delete tst, which is an static object... and that is what makes your application crash. Either you don't use setParent or you should change TstWidgetHolder::setParent to:

void TstWidgetHolder::setParent(QWidget* obj)
{
   TstWidgetHolder::wobj = new TestWidget(obj);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top