[Interest] moveToThread used in constructor to move "this"

Lorenz Haas lykurg at gmail.com
Wed Feb 24 09:39:39 CET 2016


Hi,

keep calm, it is not about moveToThread(this) :)

One canonical way to use QObjects and QThreads is this

void SomeClass::init() {
    // m_thread is a member of SomeClass
    Foo *foo = new Foo; // Foo inherits QObject
    foo->moveToThread(&m_thread);
}

So in my case I want that an instance of Foo is always moved to a
(single) thread. In order to take this knowledge/requirement - as well
as the boilerplate code - from the caller (here SomeClass::init) I am
curious if this is would be a valid substitution:

Foo::Foo() : QObject(nullptr) {
    // m_thread is now a member of Foo
    moveToThread(&m_thread);
}

void SomeClass::init() {
    Foo *foo = new Foo;
}


I guess that in the constructor of Foo the base class QObject is
already instantiated and since moveToThread only has implications on
QObject it should be right.
Can any one with deeper QThread insight confirm that using
moveToThread in a constructor like above is safe?


Thanks,
Lorenz



More information about the Interest mailing list