Solved QTcpServer copy constructor
-
Why the copy constructor of QTcpServer is private?
So instead of this:
//server.h class Server : public QObject { Q_OBJECT private: QTcpServer tcpServer; public: explicit Server(QObject *parent = nullptr); };
//server.cpp Server::Server(QObject *parent) : QObject(parent) { tcpServer = QTcpServer(); }
I am forced to use pointer to an object, like this:
//server.h class Server : public QObject { Q_OBJECT private: QTcpServer* tcpServer; public: explicit Server(QObject *parent = nullptr); };
//server.cpp Server::Server(QObject *parent) : QObject(parent) { tcpServer = new QTcpServer(); }
I believe it is not memory safe, am I wrong?
-
You just have to make sure to delete the pointer when it is no longer needed (e.g. in the dtor).
Or pass a valid parent so it gets automatically deleted when the parent is deleted - see http://doc.qt.io/qt-5/objecttrees.html -
Oh, so I can set
this
(in my case) as a parent of mytcpServer
and it will be automatically destroyed with theServer
destruction?Seems a bit tricky
-
@nevdokimof
Whole Qt is designed about this system.
Its works really well and free you from the burden of deleting all the widgets manually.
The reason the copy constructor is disabled is that you are not allowed to clone most Qt objects
due to identity and the signal and slot system.
Its all explained in the link mr @Christian-Ehrlicher shows. -
Hi, just a side note, it is perfectly valid to allocate a
QObject
on the stack.class Server : public QObject { Q_OBJECT private: QTcpServer tcpServer; public: explicit Server(QObject *parent = nullptr); }; Server::Server(QObject *parent) : QObject(parent){}
is perfectly fine.
What you are having trouble with istcpServer = QTcpServer();
which is unnecessary in C++. If you need to pass arguments to the constructors of yourQObject
s you can do it via the initializer list