[Development] QVector: clear while keeping capacity

Allan Sandfeld Jensen kde at carewolf.com
Wed Nov 5 14:33:00 CET 2014


On Wednesday 05 November 2014, Milian Wolff wrote:
> Hello all,
> 
> could it be that QVector changed its behavior in Qt5? I just noticed that
> resize(0) does deallocate memory, which is highly unexpected from my side.
> See e.g. this old thread where it was said to use resize(0) to clear a
> vector while keeping its capacity:
> 
> http://comments.gmane.org/gmane.comp.lib.qt.general/42277,using
> 
> But now in Qt5, I see in QVector::reallocData
> 
>     if (aalloc != 0) {
>        ...
>     } else {
>         x = Data::sharedNull();
>     }
> 
> which triggers the deallocation of the memory. This can be seen by this
> example program:
> 
> #include <QVector>
> #include <QDebug>
> 
> int main()
> {
>   QVector<int> v;
>   v.fill(1, 100);
>   qDebug() << v.size() << v.capacity();
>   v.resize(0);
>   qDebug() << v.size() << v.capacity();
>   v.fill(1, 100);
>   qDebug() << v.size() << v.capacity();
>   v.clear();
>   qDebug() << v.size() << v.capacity();
>   return 0;
> }
> 
> The output is for me:
> 100 122
> 0 0
> 100 122
> 0 0
> 
> Is this truly desired behavior? It can trigger serious performance
> issues...

You need to use QVector::reserve() to reserve space. If you do, then resize 
should not auto shrink. I think that is fair behaviour. Anyone who knows how 
big the vector should be, should use reserve. 

Regards
`Allan




More information about the Development mailing list