[prev in list] [next in list] [prev in thread] [next in thread]
List: kde-devel
Subject: QHash: two questions concerning memleak and key type
From: Stefan Majewsky <stefan.majewsky () googlemail ! com>
Date: 2011-07-29 21:34:23
Message-ID: CACoMYZZ4DzvY+tycJE5Ftbd-N_x7oALmAJFqJENs86YN6DbkEg () mail ! gmail ! com
[Download RAW message or body]
Hi,
I have a C++ class that implements a Composite pattern. Relevant code follows:
-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----
class Compound : public Entity {
void addChild(const QByteArray& key, Entity* newChild)
{
Q_D(Compound);
Entity*& child = d->m_children[key];
delete child;
child = newChild;
}
~Compound()
{
Q_D(Compound);
typedef QHash<QByteArray, Entity*>::const_iterator Iterator;
Iterator it1 = d->m_children.constBegin();
const Iterator it2 = d->m_children.constEnd();
for (; it1 != it2; ++it1)
delete it1.value();
}
};
-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----
If I run valgrind --leak-check=full against some example code
instantiating a tree of Compound and Entity instances, it complains
about a memleak in the second line of Compound::addChild. It says that
QHash::detach_helper allocates a few bytes which are definitely lost.
Strange thing is that the ~QHash destructor gets called; the QHash
instance is a direct member of CompoundPrivate. And now this: The
memleak vanishes (at least from Valgrind's point of view) when I
insert d->m_children.clear() at the end of ~Compound. I'm puzzled;
what's going on here? BTW the same memleak also occurs with QMap.
And while we're on that topic, I have a second question: When
designing an API, should I prefer QByteArray or QString as the key for
QHash? That key is only used in code and possibly a binary
serialization format. I'm unsure whether QString induces a performance
hit.
Greetings
Stefan
>> Visit http://mail.kde.org/mailman/listinfo/kde-devel#unsub to unsubscribe <<
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic