简体   繁体   中英

_CrtIsValidHeapPointer(block) error was raised when exit main window, after applied Singleton-Paterrn

I'm developing a Qt desktop app on windows.In main windows,I need to add a widget to my Tab Widget,it's usually wrote like down below:

void MainWindow::setConfParas()
    {
        ConfParas *confparas=new ConfParas();
        ui->TabWidget->addTab(confparas,"Configure Parameters");
    }

And I'm trying to apply Singleton Pattern to my ConfParas class, and it designs like this

class ConfParas : public QWidget
{
    Q_OBJECT

public:
    static ConfParas* getInstance()
    {
        static ConfParas theConfParas;
        return &theConfParas;
    }
    explicit ConfParas(QWidget *parent = 0);
    ConfParas(const ConfParas&)=delete;
    ConfParas& operator=(const ConfParas&)=delete;
    //sth else...
}

the former code will be wrote like:

void MainWindow::setConfParas()
    {
        ConfParas *confparas=ConfParas::getInstance();
        ui->TabWidget->addTab(confparas,"Configure Parameters");
    }

and the compiler doesn't make any error message,I can easily launch the app, but when I close the main window, _CrtIsValidHeapPointer(block) error was raised !!! so I guess it happens in the period of main window deconstructing .

When you pass a pointer to a QObject , Qt takes over the lifetime of that pointer. It assumes the memory was dynamically allocated, and then calls delete when it's time to deallocate. An exception to this rule is if a child is destroyed before its parent.

Refer to https://doc.qt.io/archives/4.6/objecttrees.html

Your static member is declared on the stack, and is managed by the runtime. When you pass it to a QObject , you're begging for a double-delete. That is, you call QTabWidget::AddTab which delegates ownership to the QTabWidget . This QTabWidget , a non-static variable will be destroyed before any static variables (your QWidget ). Since it is the parent, it will also delete its children (your QWidget ), and then when main ends it will also call the destructor of your static QWidget , hence a double-delete.

If you made your static member a pointer that was allocated on first call, then you wouldn't have this problem. In fact, I know some developers that would say this isn't really a problem anyway (not saying I agree with them) because what's the point of cleaning a building before you demolish it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM