简体   繁体   中英

Qt object ownership memory leak

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?

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).

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM