edit: sipa’s responses didn’t automatically load so the below is slightly outdated.
shrink_to_fit
exists only on vectors
std::deque also has it, as well as e.g. our prevector
Actually, with this change I’ve found that this PR is using ClearShrink
on 2 other types: bitdeque<> m_header_commitments
and std::deque<CompressedHeader> m_redownloaded_headers
.
Also, why is there a need to enforce it?
I’m not sure if we need to, I’m just raising the question. The main reason I’m considering is that we’re currently only unit testing this on a std::vector
and it seems a pretty specific function. Keeping usage in line with documentation and testing seems a sane thing to do, but again, it’s just a consideration.
Finally, your suggestion would require the caller to specify the type V for every call, which seems suboptimal.
Hmm, can you elaborate? This diff compiles fine for me:
0diff --git a/src/headerssync.cpp b/src/headerssync.cpp
1index f891063cd2..09327a33fd 100644
2--- a/src/headerssync.cpp
3+++ b/src/headerssync.cpp
4@@ -52,9 +52,9 @@ HeadersSyncState::HeadersSyncState(NodeId id, const Consensus::Params& consensus
5 void HeadersSyncState::Finalize()
6 {
7 Assume(m_download_state != State::FINAL);
8- ClearShrink(m_header_commitments);
9+ m_header_commitments = {};
10 m_last_header_received.SetNull();
11- ClearShrink(m_redownloaded_headers);
12+ m_redownloaded_headers = {};
13 m_redownload_buffer_last_hash.SetNull();
14 m_redownload_buffer_first_prev_hash.SetNull();
15 m_process_all_remaining_headers = false;
16diff --git a/src/util/vector.h b/src/util/vector.h
17index 2e83eb181b..09a9c409d4 100644
18--- a/src/util/vector.h
19+++ b/src/util/vector.h
20@@ -51,7 +51,7 @@ inline V Cat(V v1, const V& v2)
21
22 /** Clear a vector and release its allocated memory. */
23 template<typename V>
24-inline void ClearShrink(V& v) noexcept
25+inline void ClearShrink(std::vector<V>& v) noexcept
26 {
27 // There are various ways to clear a vector and releasing its memory:
28 //
29@@ -64,7 +64,7 @@ inline void ClearShrink(V& v) noexcept
30 // follows. (3) and (4) rely on std::vector::shrink_to_fit, which is only a non-binding
31 // request. Therefore, we use method (1).
32
33- V{}.swap(v);
34+ std::vector<V>{}.swap(v);
35 }
36
37 #endif // BITCOIN_UTIL_VECTOR_H