PDA

View Full Version : creating/deleting Objects // memory leaks



janus
27th March 2008, 16:58
hi,
since a year or so I am learning to use c++ and qt. I have writen a small app and since Qt is quite easy to use and well documented it works all fine. But i guess their are still alot of things i can improve. I have a question regarding memory leaks and the cration of objects. I did not take very much care of that so far (maybe a silly question):
As far as I understand childobjects are destroyed when the parent is destroyed. What does that mean when I use e.g. a QSqlTableModel or a QTableView etc.. Do I have to create them allways like ... = new QSqlTableModel(this) instead of ... = new QSqlTableModel ?
Is the model not destroyed after the mainwindow is closed when i create it without assigning it to a parent (the QMainWindow) ?

jpn
27th March 2008, 17:25
As far as I understand childobjects are destroyed when the parent is destroyed.
That's correct. But that's all, there is no black magic like that all QObjects would get somehow cleaned up. They won't unless they have a parent AND their parent gets deleted. If the parent isn't deleted, children aren't either.


What does that mean when I use e.g. a QSqlTableModel or a QTableView etc.. Do I have to create them allways like ... = new QSqlTableModel(this) instead of ... = new QSqlTableModel ?
Is the model not destroyed after the mainwindow is closed when i create it without assigning it to a parent (the QMainWindow) ?
No, the model isn't destroyed unless you pass a parent.

janus
27th March 2008, 17:53
thank you
just a clarification for a beginner :-) :

I should not use this code examples from the docs (QSqlQueryModel Class Reference) ...



QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("SELECT name, salary FROM employee");
model->setHeaderData(0, Qt::Horizontal, tr("Name"));
model->setHeaderData(1, Qt::Horizontal, tr("Salary"));


without adding ... = new QSqlQueryModel(this); ?

I guess everyone knows (besides me .-)

jpn
27th March 2008, 18:14
Well, of course those example snippets expect you to know the basic concepts of the library itself and also the used programming language. :) Like if you create a model on the stack like in the next example snippet, it might go out of scope unless there's for example QApplication::exec() which blocks. It's always the same problem with example code snippets. If there was "this" then people would surely ask what's "this" referring to. Usually it's pointless to make example snippets complete for the sake of clarity and readability.

janus
27th March 2008, 18:17
yes, you are right. Anyway, now i am going to add many "this(es)" to my little app .-)
thx