Reputation: 3127
I am reading an introduction book to Qt and I am writing this code:
server.h
class server : public QObject {
Q_OBJECT
private:
QTcpServer* chatServer;
public:
explicit server(QObject *parent = nullptr) : QObject(parent) {}
//more code...
};
#endif // SERVER_H
Then the book suggests to create the object in this way:
chatServer = new QTcpServer(); //<-- ?)
chatServer->setMaxPendingConnections(10);
I have read online that Qt has an hierarchy because everything descends frm QObject
and the parent object will take care of the life of the children. In this case, doesnt the code generate a memory leak?
Because chatServer = new QTcpServer();
is equal to chatServer = new QTcpServer(nullptr);
and so I am not specifying a parent! So there is nobody that takes care of the life of this object in the heap. Do I have to call the delete
(or better use an unique_ptr ) to manage the memory?
Another fix that I'd use would be chatServer = new QTcpServer(server);
. Would this be ok?
Upvotes: 0
Views: 683
Reputation: 453
This does indeed seem to be a memory leak. chatServer
should have this
as its parent so it will be automatically destroyed with the server
object:
chatServer = new QTcpServer(this);
chatServer->setMaxPendingConnections(10);
// ... more code
Assuming that this happens inside a member function of the server
class, this would parent the QTcpServer
object to the server
object.
If the book provides no specific reason to make the QTcpServer
object dynamically allocated, it is probably not necessary. In that case, as Dan M. says, it is entirely possible to not use a pointer at all and simply have QTcpServer chatServer
Upvotes: 3
Reputation: 1974
In the example you posted, you have to take care of the pointer for yourself.
But instead of calling delete
, you may want to use the QObject's slot deleteLater
.
Upvotes: 0
Reputation: 4052
If this code is indeed all that's shown in your book, then you are correct. If you don't pass the parent to QTcpServer
it won't be automatically deleted when your object is destroyed. You can also do that manually in the destructor or maybe even better - just don't use the pointer and use it directly (though you may need to use pointer if you, for example, decide to move the object to another thread).
Upvotes: 3