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?