QObject
parentage and storage duration are orthogonal issues and should be addressed separately.
You cannot move a QObject
holding other QObject
s to another thread, unless all the owned objects have the owner set as a parent. Thus, by not setting the parent, you're prematurely limiting the functionality of the parent class.
In modern C++, child QObject
s with dynamic storage duration should be held via a resource manager. Such a manager can be a smart pointer, or simply the owning object. Recall that a QObject
is also, implicitly, a QObject
container. Because of that, it's not even necessary to have an explicit member pointer to the child object - say if you're only needing to refer to the object directly during construction of the owner.
Generally speaking, by having any members with dynamic storage duration, you're prematurely pessimizing unless their constructors are very expensive and you would want to delay construction until a later point.
So, if you're not using the PIMPL idiom, then all members should have automatic storage duration in the object itself:
// A.h
class A : public QObject {
Q_OBJECT
QSerialPort m_port { this };
QThread m_thread { this };
....
};
Otherwise, they belong in the PIMPL:
// A.h
class APrivate;
class A : public QObject { ... };
// A.cpp
#include "A.h"
class APrivate {
public:
A * const q_ptr;
QSerialPort m_port { q_ptr };
QThread m_thread { q_ptr };
APrivate(A * q) : q_ptr(q) {}
};
It should also be pointed out that using pointers to forward-declared incomplete types in order to "speed up" compilation or "decrease dependencies" is an anti-pattern. If you are willing to expose implementation details in a header file, just hold all the members you can by value - as in the first example above. If you're worried about excessive dependencies and want to hide your implementation, use the PIMPL. The "middle road" of pointers-to-forward-declared-classes forces extra dynamic storage allocations upon you and is thus an inflexible monstrosity that helps nothing and no-one.
// DO NOT WRITE CODE LIKE THIS!!
class QSerialPort;
class QThread;
class A : public QObject {
Q_OBJECT
QSerialPort * m_port;
QThread * m_thread;
...
};
// DO NOT WRITE CODE LIKE THIS!!