From 53443b537075cb3ad0ce153596c79f442320f268 Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Sun, 19 Nov 2017 22:09:37 +0100 Subject: [PATCH] Add wxVector::shrink_to_fit() for C++11 compatibility Also use this for wxArray::Shrink() implementation as it's more efficient than the old swap-based implementation which requires an extra memory allocation instead of really shrinking the existing one. --- include/wx/vector.h | 6 ++++++ interface/wx/vector.h | 12 ++++++++++++ tests/vectors/vectors.cpp | 24 ++++++++++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/include/wx/vector.h b/include/wx/vector.h index aa74c6586e..df99c6b0c0 100644 --- a/include/wx/vector.h +++ b/include/wx/vector.h @@ -375,6 +375,12 @@ public: return m_capacity; } + void shrink_to_fit() + { + m_values = Ops::Realloc(m_values, m_size, m_size); + m_capacity = m_size; + } + bool empty() const { return size() == 0; diff --git a/interface/wx/vector.h b/interface/wx/vector.h index 0f55c1b460..60d953d94b 100644 --- a/interface/wx/vector.h +++ b/interface/wx/vector.h @@ -262,6 +262,18 @@ public: void resize(size_type n, const value_type& v); //@} + /** + Free unused memory allocated by the vector. + + Reduces the memory used by the vector to the bare minimum required to + hold its current number of elements, possibly 0. + + After calling this method, capacity() returns the same as size(). + + @since 3.1.1 + */ + void shrink_to_fit(); + /** Returns the size of the vector. */ diff --git a/tests/vectors/vectors.cpp b/tests/vectors/vectors.cpp index 92517636ef..8495cdca58 100644 --- a/tests/vectors/vectors.cpp +++ b/tests/vectors/vectors.cpp @@ -361,3 +361,27 @@ TEST_CASE("wxVector::reverse_iterator", "[vector][reverse_iterator]") CHECK( ri - rb == 2 ); CHECK( re - ri == 8 ); } + +TEST_CASE("wxVector::capacity", "[vector][capacity][shrink_to_fit]") +{ + wxVector v; + CHECK( v.capacity() == 0 ); + + v.push_back(0); + // When using the standard library vector, we don't know what growth + // strategy it uses, so we can't rely on this check passing, but with our + // own one we can, allowing us to check that shrink_to_fit() really shrinks + // the capacity below. +#if !wxUSE_STD_CONTAINERS + CHECK( v.capacity() > 1 ); +#endif + + v.shrink_to_fit(); + CHECK( v.capacity() == 1 ); + + v.erase(v.begin()); + CHECK( v.capacity() == 1 ); + + v.shrink_to_fit(); + CHECK( v.capacity() == 0 ); +}