Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime of Qt Objects

What are the lifetimes of Qt Objects?

Such as:

QTcpSocket *socket=new QTcpSocket();

When socket will be destroyed? Should I use

delete socket;

Is there any difference with:

QTcpSocket socket;

I couldn't find deep infromation about this, any comment or link is welcomed.

like image 632
metdos Avatar asked Jul 16 '10 11:07

metdos


2 Answers

Qt uses parent-child relationships to manage memory. If you provide the QTcpSocket object with a parent when you create it, the parent will take care of cleaning it up. The parent can be, for example, the GUI window that uses the socket. Once the window dies (i.e. is closed) the socket dies.

You can do without the parent but then indeed you have to delete the object manually.

Personally I recommend sticking to idiomatic Qt and using linking all objects into parent-child trees.

like image 180
Eli Bendersky Avatar answered Oct 16 '22 22:10

Eli Bendersky


Objects allocated with new must be released with delete.

However, with Qt, most objects can have a parent, which you specify as an argument to the constructor. When the parent is deleted, the child objects get deleted automatically.

like image 40
Alexandre C. Avatar answered Oct 16 '22 22:10

Alexandre C.