PDA

View Full Version : Calling destructor for classes with QWidget or QObject as its base class



ehnuh
21st November 2012, 03:22
Hi, has anyone experienced having a segmentation error when deleting pointers in the destructor of a class? This usually happens when I close my application. I created the pointers with the new keyword. These pointers are also classes with a base class of qobject or qwidget. Do I still need to destroy them? or are they automatically destroyed. When I run my app in debug mode, the breakpoints stop in the destructor and does not cause an error, but when I run it normally, it crashes.

ChrisW67
21st November 2012, 05:23
Hi, has anyone experienced having a segmentation error when deleting pointers in the destructor of a class?
Sure, if you haven't then you are not trying hard enough ;)

This usually happens when I close my application. I created the pointers with the new keyword. These pointers are also classes with a base class of qobject or qwidget. Do I still need to destroy them? or are they automatically destroyed.
Yes. All the rules of C++ memory management apply to programs using Qt: all allocated memory must be freed and you are responsible for ensuring that happens. There are several ways to do this, and not all of them involve explicitly calling delete. In Qt programs if you create a QObject with a QObject parent, or set one later, then the parent QObject owns it and will delete it. Parentless QObjects are the same as any other C++ object and you will have to delete. There are various forms of smart pointer that can handle allocated memory on your behalf.

When I run my app in debug mode, the breakpoints stop in the destructor and does not cause an error, but when I run it normally, it crashes.
You are:

Deleting something that has already been deleted (double-free)
Deleting something and then trying to use it
Doing other obscure things

ehnuh
22nd November 2012, 05:03
thanks for the info sir!