PDA

View Full Version : QHash, QList - are destructors called on remove?



qtYoda
21st March 2011, 05:48
Suppose you have

A: QList<myClass> myClassList;
B: QList<myClass *> myClassList;

When a remove is called (removeOne or clear, etc.) in cases A & B, are destructors called for myClass? Does the answer differ if using QHash or QQueue?

I thought the destructor was called in B, but not A .

Zlatomir
21st March 2011, 06:50
The destructor is called in case A (in case you have objects in your container) and not in case B most likely because it's wrong to call delete on a pointer if you only assume it was used to allocate heap memory (that pointer could be pointing to stack memory).

So if you use container of pointers and allocate heap memory for objects you need to delete that memory before each element is removed from container and delete memory for all elements before the container goes out of scope.

//i don't see a reason for you to use a QHash (http://doc.trolltech.com/4.7/qhash.html) or a QMap of pointers, but maybe i just didn't find it yet ;)

wysota
21st March 2011, 08:18
if myClass inherits QObject then pointers have to be used.

Zlatomir
21st March 2011, 08:48
@Wysota: is this only because QObjects are not "copyable" (since each QObject has unique meta-data and private copy constructor and assignment operator) or there are other reasons that i don't get?
Anyway thanks for the correction ;)

wysota
21st March 2011, 08:56
This is because of the reason why QObjects are not copiable. This is because they are "identity based" and not "value based". Each QObject is a separate and complete "citizen" with its own "personality" - that's why you can't copy it. Ans since you can't copy it, you can't put it into a container that requires its values to be well... values and not identities.

qtYoda
21st March 2011, 16:26
The objects I'm managing (well, trying to manage) are QTcpSockets. So they're QObjects. I log them into a QList so that I can shut them down from my server if it exits before the sockets are disconnected and deleted.

Somewhere I've got a bug and it seems to be when I remove a socket from the list. I thought maybe the QList was calling the destructor -- which I wasn't counting on -- but it seems that it won't because the QList is just holding a pointer. So I'll keep hunting. Thanks.

qtYoda
22nd March 2011, 15:17
Reworked the socket server/handler without any collections -- only signals/slots --- and all working fine for now.