0

I'm writing an app in QT. I'd like to use QButtonGroup, so I declear it in header file of user interface class:

std::unique_ptr<QButtonGroup> examTypeSelectGroup;

But when I close application, I recive the error:

Run-Time Check Failure #2 - Stack around the variable 'w' was corrupted.

in last line of main.cpp file, which was a mian file of a project. Call stack when error occures have only main():

>   OCT_main.exe!main(int argc, char * * argv) Line 14
    [External Code]

Error occures both, when I tried to use object, and when I don't use it (just declare it). Have you got any idea, what happend.

main.cpp:

1   #include "oct_main.h"
2
3   #include <QApplication>
4
5   int main(int argc, char *argv[])
6   {
7       QApplication a(argc, argv);
8
9       //run window
10      OCT_main w;
11      w.show();
12
13      return a.exec();
14  }

EDIT: using QButtonGroup examTypeSelectGroup; make error during destruct a button group, so it was bad way too.

Miziol
  • 42
  • 8
  • Please provide a [mcve]. Also note that `Qt` has its own ownership model in the parent/child object hierarchy so I suspect both `Qt` and your `std::unique_ptr` are calling `delete` on the same pointer value. Hence the memory corruption. – G.M. Jul 23 '21 at 07:40
  • Ok, sa can I use normal pointer, a can be shure that memory was managed well, Or better way is @Julien-Lopez suggestion, to use QT Smart Pointers? – Miziol Jul 23 '21 at 07:46
  • 1
    @Miziol, you can use raw pointers for your Qt class objects (QObjects and layouts). In the same time, as said, you should make sure you properly established parent/child relationship of our objects - Qt framework will take care of the rest. – vahancho Jul 23 '21 at 08:44

1 Answers1

2

First rule of Qt (more precisely, any QObject derived class), never call delete on it.

So a basic unique_ptr like you are using is probably a bad idea, you either have to write a custom deleter to call deleteLater(), or use Qt's own smart pointers

https://wiki.qt.io/Smart_Pointers

And even then, I don't think they provide smart pointers working with QObject derived classes.

Qt has an older style memory management, so it doesn't mix well with the new standard stuff out of the box.

Julien Lopez
  • 1,021
  • 6
  • 14