Op 24/02/2016 om 09:39 schreef Lorenz Haas:
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?

That should work just fine, with the exception of using &m_thread as a member. If you want to use the class as you write it above, then there is no way to set that member. You will probably need to use some form of a static here, either inside the class itself if you don't need control over the actual thread creation itself, or externally, perhaps wrapped in some kind of singleton.

André
_______________________________________________
Interest mailing list
Interest@qt-project.org
http://lists.qt-project.org/mailman/listinfo/interest

Reply via email to