[libcxx-commits] [libcxx] Fix capacity increase issue with `shrink_to_fit` for `__split_buffer` (PR #117720)
Peng Liu via libcxx-commits
libcxx-commits at lists.llvm.org
Tue Nov 26 07:04:19 PST 2024
https://github.com/winner245 created https://github.com/llvm/llvm-project/pull/117720
This PR fixes the issue where `__split_buffer::shrink_to_fit` may unexpectedly increase the capacity, similar to the issue for `std::vector` in #97895. A [demo](https://godbolt.org/z/reEEGMnz4) to reproduce this problem is available. The fix follows the same approach used in #97895 for `std::vector`.
Note: An alternative approach would be simply remove this function. However, the current fix is as simple as removing it.
>From b6fe9f9f60154d87a2f3f76ba444051a09f01380 Mon Sep 17 00:00:00 2001
From: Peng Liu <winner245 at hotmail.com>
Date: Tue, 26 Nov 2024 10:01:22 -0500
Subject: [PATCH] Fix __split_buffer::shrink_to_fit
---
libcxx/include/__split_buffer | 14 ++++++++------
1 file changed, 8 insertions(+), 6 deletions(-)
diff --git a/libcxx/include/__split_buffer b/libcxx/include/__split_buffer
index a44811c766735a..a637c83d17d107 100644
--- a/libcxx/include/__split_buffer
+++ b/libcxx/include/__split_buffer
@@ -410,12 +410,14 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 void __split_buffer<_Tp, _Allocator>::shrink_to_fi
try {
#endif // _LIBCPP_HAS_EXCEPTIONS
__split_buffer<value_type, __alloc_rr&> __t(size(), 0, __alloc_);
- __t.__construct_at_end(move_iterator<pointer>(__begin_), move_iterator<pointer>(__end_));
- __t.__end_ = __t.__begin_ + (__end_ - __begin_);
- std::swap(__first_, __t.__first_);
- std::swap(__begin_, __t.__begin_);
- std::swap(__end_, __t.__end_);
- std::swap(__cap_, __t.__cap_);
+ if (__t.capacity() < capacity()) {
+ __t.__construct_at_end(move_iterator<pointer>(__begin_), move_iterator<pointer>(__end_));
+ __t.__end_ = __t.__begin_ + (__end_ - __begin_);
+ std::swap(__first_, __t.__first_);
+ std::swap(__begin_, __t.__begin_);
+ std::swap(__end_, __t.__end_);
+ std::swap(__cap_, __t.__cap_);
+ }
#if _LIBCPP_HAS_EXCEPTIONS
} catch (...) {
}
More information about the libcxx-commits
mailing list