Skip to content

Commit 8458bbe

Browse files
authored
[libc++] Fix capacity increase issue with shrink_to_fit for __split_buffer (#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. The fix follows the same approach used in #97895 for `std::vector`.
1 parent 105b780 commit 8458bbe

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

libcxx/include/__split_buffer

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -410,12 +410,14 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 void __split_buffer<_Tp, _Allocator>::shrink_to_fi
410410
try {
411411
#endif // _LIBCPP_HAS_EXCEPTIONS
412412
__split_buffer<value_type, __alloc_rr&> __t(size(), 0, __alloc_);
413-
__t.__construct_at_end(move_iterator<pointer>(__begin_), move_iterator<pointer>(__end_));
414-
__t.__end_ = __t.__begin_ + (__end_ - __begin_);
415-
std::swap(__first_, __t.__first_);
416-
std::swap(__begin_, __t.__begin_);
417-
std::swap(__end_, __t.__end_);
418-
std::swap(__cap_, __t.__cap_);
413+
if (__t.capacity() < capacity()) {
414+
__t.__construct_at_end(move_iterator<pointer>(__begin_), move_iterator<pointer>(__end_));
415+
__t.__end_ = __t.__begin_ + (__end_ - __begin_);
416+
std::swap(__first_, __t.__first_);
417+
std::swap(__begin_, __t.__begin_);
418+
std::swap(__end_, __t.__end_);
419+
std::swap(__cap_, __t.__cap_);
420+
}
419421
#if _LIBCPP_HAS_EXCEPTIONS
420422
} catch (...) {
421423
}

0 commit comments

Comments
 (0)