QThread and pointers
-
Hi,
i have a question about QThread and pointers. I move my worker object to a created QThread (https://forum.qt.io/topic/66408/qthread-in-main-function). In the worker object there a pointers to other objects. These objects are created in a slot (so they are in a separate thread). Some pointers are shared with other objects.I'm not sure in which thread the pointers live in and if this is allowed or can occure some errors.
My code looks like this
class WorkerObject: public QObject { Q_OBJECT public Q_SLOTS: void createMembers() // create objects in a other thread { m_myObject1 = new MyObject1(); QObject::connect(this, &QObject::destroyed, m_myObject1, &Qbject::deleteLater); m_myObject2 = new MyObject2(m_myObject1); QObject::connect(this, &QObject::destroyed, m_myObject2, &Qbject::deleteLater); ... } private: MyObject1 *m_myObject1; MyObject2 *m_myObject2; ... };
-
Is createMembers() called before or after you move the object to other thread?
Do you use queued connection?
Is it necessary to create these objects on the heap via new? -
Then it should be OK.
The slot is executed in the thread where the object resides, so the objects are created in the same thread.
Regarding sharing the pointers with other objects: in which thread are those other objects? -
@beecksche said:
CreateMembers() is called after i moved the workobject to the thread.
It makes a whole lot of difference how you call it. Is it connected to a signal, do you call it explicitly?
-
@beecksche
Then it's perfectly fine. -
@beecksche
No worries.
Although,QScopedPointer
might be appropriate here (looking at your code), you may want to check it out. -
@beecksche said:
The advatage of a QScopedPointer is that you don't have to care about the destruction of the object, right?
Yes. It's a thin wrapper around the raw pointer and will
delete
the held reference when it goes out of scope. The idea is to use the stack basedQScopedPointer
object to manage the heap-allocated object it's referencing.Kind regards.