[Development] Releasing memory after clear() in Qt containers (Qt 5.X)

Francesc Martinez francescmm at gmail.com
Sat Apr 24 09:04:38 CEST 2021

Hi Giuseppe,

Thanks for the help! I'll try to answer one by one to your questions.

1) clear() on a container doesn't (necessarily) release all the memory
> held by that container. For instance std::vector / Q5Vector retain the
> allocated capacity:

 A Q5Hash will release the memory held by the objects in the hash (as

they're individually allocated) but may or may not (need to check the
> code) shrink the bucket array.
> If you want to truly release all the memory used by a container, then
> either
> *) use shrink_to_fit / squeeze after clear,
> *) or move-assign an empty container,
> *) or swap with an empty container.

I personally thought that deallocating the data contained in a
QHash/QVector and removing the class that have those parameters would do
the trick, but I've been testing the squeeze() method and it does seems to
improve it a lot. Thank you so much!

I'll keep investigating on that and trying to make some improvements in
this area. I'd like the app to hold for weeks if needed, so let's see what

2) How are you measuring memory usage precisely? Looking at 'top' or
> 'Task manager' is the wrong way, you need a memory profiler (like
> heaptrack on Linux).

As you say, Task Manager is not the tool for that, but it was the one that
brought this into my attention. I've been using the VisualStudio memory
profiler (and Deleaker) and also heaptrack (that's a great tool btw). I
could have shared the heaptrack output probably.

3) Unrelated to your problem, your code works in Qt 5, but in Qt 6 if
> the QHash gets modified in any way that'll invalidate your entire
> QVector you're keeping as a cache. If you want to future proof your code
> you'll need to redesign that.

Yep, I'm totally aware of that although I don't have any plans for a
migration to Qt6 until all the modules are ported and I see some stability
in there. Most of the current Linux distros are not even using Qt 5.15, so
I'm fine for some time. But thanks for the heads-up!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20210424/a96fd6c8/attachment.html>

More information about the Development mailing list