diff options
author | Pieter Wuille <pieter@wuille.net> | 2023-09-11 13:54:32 -0400 |
---|---|---|
committer | fanquake <fanquake@gmail.com> | 2023-09-26 16:26:55 +0100 |
commit | 67b6d99aead0d1b2030bc3e88256d279477894b5 (patch) | |
tree | 6d91265102584b5ee38da2511e6b4972c48c3dba /src/util/vector.h | |
parent | defdc1502372863f700720e8d5cde69190371a64 (diff) |
Do not use std::vector = {} to release memory
Github-Pull: #28452
Rebased-From: 3fcd7fc7ff563bdc0e2bba66b4cbe72d898c876e
Diffstat (limited to 'src/util/vector.h')
-rw-r--r-- | src/util/vector.h | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/src/util/vector.h b/src/util/vector.h index ed745affe5..bc62b64d28 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 |