QVarLengthArray: add squeeze function

Add function to move back data to the stack.

Change-Id: Ic78a368459bce68629e29602e4eeae2e1afe398b
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
Peter Kümmel 2012-10-10 16:35:44 +02:00 committed by The Qt Project
parent ff31462e73
commit 70a9caf4de
3 changed files with 46 additions and 3 deletions

View File

@ -103,6 +103,7 @@ public:
inline bool isEmpty() const { return (s == 0); }
inline void resize(int size);
inline void clear() { resize(0); }
inline void squeeze();
inline int capacity() const { return a; }
inline void reserve(int size);
@ -243,6 +244,10 @@ Q_OUTOFLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::append(const T *abuf, in
}
}
template <class T, int Prealloc>
Q_INLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::squeeze()
{ realloc(s, s); }
template <class T, int Prealloc>
Q_OUTOFLINE_TEMPLATE void QVarLengthArray<T, Prealloc>::realloc(int asize, int aalloc)
{

View File

@ -210,7 +210,7 @@
initialized. For other types, the elements are initialized with a
\l{default-constructed value}.
\sa size()
\sa size(), squeeze()
*/
/*! \fn int QVarLengthArray::capacity() const
@ -223,7 +223,7 @@
need to call this function. If you want to know how many items are
in the array, call size().
\sa reserve()
\sa reserve(), squeeze()
*/
/*! \fn void QVarLengthArray::reserve(int size)
@ -240,7 +240,21 @@
rarely ever need to call this function. If you want to change the
size of the array, call resize().
\sa capacity()
\sa capacity(), squeeze()
*/
/*! \fn void QVarLengthArray::squeeze()
\since 5.1
Releases any memory not required to store the items.
If the container can fit its storage on the stack allocation,
it will free the heap allocation and copy the elements back to the stack.
The sole purpose of this function is to provide a means of fine
tuning QVarLengthArray's memory usage. In general, you will rarely ever
need to call this function.
\sa reserve(), capacity(), resize()
*/
/*! \fn T &QVarLengthArray::operator[](int i)

View File

@ -58,6 +58,7 @@ private slots:
void count();
void first();
void last();
void squeeze();
};
int fooCtor = 0;
@ -653,5 +654,28 @@ void tst_QVarLengthArray::last()
QCOMPARE(list.length(), 1);
}
void tst_QVarLengthArray::squeeze()
{
QVarLengthArray<int> list;
int sizeOnStack = list.capacity();
int sizeOnHeap = sizeOnStack * 2;
list.resize(0);
QCOMPARE(list.capacity(), sizeOnStack);
list.resize(sizeOnHeap);
QCOMPARE(list.capacity(), sizeOnHeap);
list.resize(sizeOnStack);
QCOMPARE(list.capacity(), sizeOnHeap);
list.resize(0);
QCOMPARE(list.capacity(), sizeOnHeap);
list.squeeze();
QCOMPARE(list.capacity(), sizeOnStack);
list.resize(sizeOnStack);
list.squeeze();
QCOMPARE(list.capacity(), sizeOnStack);
list.resize(sizeOnHeap);
list.squeeze();
QCOMPARE(list.capacity(), sizeOnHeap);
}
QTEST_APPLESS_MAIN(tst_QVarLengthArray)
#include "tst_qvarlengtharray.moc"