[Interest] How to get destructor called in object that was moved to a thread?

Allan Sandfeld Jensen kde at carewolf.com
Wed Aug 19 12:08:44 CEST 2015


On Wednesday 19 August 2015, Murphy, Sean wrote:
> > Where do you delete mine? I see no delete nor any ownership. Note that
> > unless you move it back you need to delete it from the body of the new
> > thread. If the new thread has a runloop you can also async call the slot
> > mine-
> > 
> > >deleteLayer().
> 
> Yeah, I mistakenly assumed that the moveToThread() call would cause the
> QThread object to take ownership of the "mine" object. So I've got that
> fixed now using Thiago's suggestion in the response following yours.
> 
I trick I often use for QThread. Since the concept of having a single 
interface to the job you are doing in the thread often makes sense, but you 
can't have it in QThread (because QThread does not live in itself), you can 
have a second object that IS living in the new QThread. You can call this 
MyJob or MyThreadMain, or whatever. This can then be owned by a smart pointer 
(QScopedPointer) inside QThread::run, and all qobjects that live in the thread 
and that needs to be deleted on thread exit can have this object as their 
parent. Also you can use signals and slots on the object to asynchronously 
feed the job with data and get results back from it. Since it is owned by 
another thread the signal will automatically become queued.

Just remember it can not be the QThread itself :)

`Allan



More information about the Interest mailing list