[Qt-interest] Question regarding QThread object affinity

Arnold Krille arnold at arnoldarts.de
Mon Jun 8 20:44:10 CEST 2009


On Monday 08 June 2009 20:14:19 Patric wrote:
> I have a question regarding threads.
> Let's assume we have a A. In that class, we have instance of class B as a
> member. We also have a QThread - class C. The class B member is not a
> pointer.
> What if I call "member_B.moveToThread()", how will the object member_B be
> deleted ? Usually, it'll be deleted when the object_A is destroyed. But now
> it's moved to another thread, who is responsible for it's deletion ?

Assuming the thread C isn't a child of object A: When you move B to the thread 
C, its owner (in the Qt-way) will change, probably to 0 as the thread itself 
can't be the new parent as the tread C lives in the main-thread (hard to 
understand at first, but QThread objects live in their creating thread, only 
stuff inside run() is in the new thread). So actually the object B will not be 
destroyed when A is killed as Qt's parent-child mechanism will not work here 
as there is no parent to B. But really the C.run() would be responsible for 
deleting the object before the end of the thread.
But when A holds a reference to B (and not a pointer) it will destroy B when 
it goes out of scope. And that might be something bad, because B might still 
be doing stuff in C and be active!

That is basicly one of the reasons why you shouldn't hold references to 
QObjects, only pointers or QPointers.

Have fun,

Arnold
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090608/d760bce1/attachment.bin 


More information about the Qt-interest-old mailing list