aboutsummaryrefslogtreecommitdiff
path: root/src/util
diff options
context:
space:
mode:
authorPieter Wuille <pieter@wuille.net>2023-09-11 13:54:32 -0400
committerPieter Wuille <pieter@wuille.net>2023-09-13 07:20:36 -0400
commit3fcd7fc7ff563bdc0e2bba66b4cbe72d898c876e (patch)
tree700c58d44de74b7dba914d5ea1083fcff90ece7c /src/util
parentfd69ffbbfb3e08b474b33540e56cf4f81e5c21d4 (diff)
Do not use std::vector = {} to release memory
Diffstat (limited to 'src/util')
-rw-r--r--src/util/vector.h18
1 files changed, 18 insertions, 0 deletions
diff --git a/src/util/vector.h b/src/util/vector.h
index 9b9218e54f..40ff73c293 100644
--- a/src/util/vector.h
+++ b/src/util/vector.h
@@ -49,4 +49,22 @@ inline V Cat(V v1, const V& v2)
return v1;
}
+/** Clear a vector (or std::deque) and release its allocated memory. */
+template<typename V>
+inline void ClearShrink(V& v) noexcept
+{
+ // There are various ways to clear a vector and release its memory:
+ //
+ // 1. V{}.swap(v)
+ // 2. v = V{}
+ // 3. v = {}; v.shrink_to_fit();
+ // 4. v.clear(); v.shrink_to_fit();
+ //
+ // (2) does not appear to release memory in glibc debug mode, even if v.shrink_to_fit()
+ // follows. (3) and (4) rely on std::vector::shrink_to_fit, which is only a non-binding
+ // request. Therefore, we use method (1).
+
+ V{}.swap(v);
+}
+
#endif // BITCOIN_UTIL_VECTOR_H