Solved Qt examples and the usage of pointers
-
@Defohin said in Qt examples and the usage of pointers:
@p3c0 How do I know when a pointer is going to leak or not in Qt?
You cannot. Just like any other pointer.
But you can Design your app so all Widgets
have a Parent and all parents are owned by
Main Window.
So just normal care is needed. -
@mrjj That is kinda tricky, I tried to use a few softwares to detect leaking but they say that even if my pointer has a parent like
new SomeClass(this)
it's "leaking", it's probably false positive, but they say it's a leak, so I have no idea when it's an actual leak or not. -
Yes its tricky.
Tools like valgrind needs tweaking to reduce the noise.
If the tool is too simple , it dont understand the delete by parent and
when it see no delete for it, flag as leak.On the bright side, its not that easy to make a leak as not assigning a parent will make it a
window and embedding a widget into something will (almost) surely own it. ( like layouts) -
@mrjj said in Qt examples and the usage of pointers:
On the bright side, its not that easy to make a leak as not assigning a parent will make it a
window and embedding a widget into something will (almost) surely own it. ( like layouts)What you mean with that? Sorry for my ignorance.
-
@Defohin
Hi
Well when I first started Qt I was also a bit sceptical about never
calling delete on my widgets. ( as in pure c++ its a leak)However, if you try to design an application and forget to assign parent, you will find it as it becomes a window.
QLabel *mine= new QLabel();
mine->show()Will popup as a window and its very clear something its up.
Also then you want to place it into some other widget, you
use layouts.
and as soon as you go
somewidget->layout()->addWidget(mine)
its owned by the layout.So its actually a bit hard to create a widget you dont want as window and create leak
without assigning a parent as it will clearly show :)That leaves mostly QDialogs and windows to leak but there you have
diag->setAttribute(Qt::WA_DeleteOnClose);
So if closed, they clean up. -
@mrjj The same happens with
QObject
? If I don't assign a parent to it? -
Yes, its actually QObject that does this Parent->Child deleting and not Qwidgets :)
But QObject dont become window. Its a QWidgets thing.
Just so we are clear. All QWidgets are QObject :)
-
@mrjj Meaning that if I don't delete QObject or assign a parent to it, it's going to leak, correct?
-
@Defohin
Yes that could happen.
http://doc.qt.io/qt-5/objecttrees.html -
@mrjj Thank you, it's really tricky, but I'll try to be careful with that.
-
@Defohin
well, you should also look into using smart pointers.
Thats how its managed in plain c++.
http://stackoverflow.com/questions/31750689/how-to-use-smart-pointer-for-auto-clean-up
https://en.wikipedia.org/wiki/Smart_pointerSmall note. Do not put smart pointers on Widgets with parents as it get ugly :)
Also Qt comes with Qt versions of those.
-
@mrjj Thank you very much.