[libcxx-commits] [libcxx] [libc++] Fix shrink_to_fit implementation for vector<bool> (PR #120495)

Peng Liu via libcxx-commits libcxx-commits at lists.llvm.org
Wed Dec 18 18:51:36 PST 2024


https://github.com/winner245 updated https://github.com/llvm/llvm-project/pull/120495

>From 98c17a25d0726fec146fa8f2eea13445a9af2fab Mon Sep 17 00:00:00 2001
From: Peng Liu <winner245 at hotmail.com>
Date: Wed, 18 Dec 2024 18:23:11 -0500
Subject: [PATCH] Fix shrink_to_fit for vector<bool>

---
 libcxx/include/__vector/vector_bool.h | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/libcxx/include/__vector/vector_bool.h b/libcxx/include/__vector/vector_bool.h
index 36eb7f350ac406..190ea2585b7821 100644
--- a/libcxx/include/__vector/vector_bool.h
+++ b/libcxx/include/__vector/vector_bool.h
@@ -841,11 +841,13 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 void vector<bool, _Allocator>::reserve(size_type _
 
 template <class _Allocator>
 _LIBCPP_CONSTEXPR_SINCE_CXX20 void vector<bool, _Allocator>::shrink_to_fit() _NOEXCEPT {
-  if (__external_cap_to_internal(size()) > __cap_) {
+  if (__external_cap_to_internal(size()) < __cap_) {
 #if _LIBCPP_HAS_EXCEPTIONS
     try {
 #endif // _LIBCPP_HAS_EXCEPTIONS
-      vector(*this, allocator_type(__alloc_)).swap(*this);
+      vector __v(*this, allocator_type(__alloc_));
+      if (__v.__cap_ < __cap_)
+        __v.swap(*this);
 #if _LIBCPP_HAS_EXCEPTIONS
     } catch (...) {
     }



More information about the libcxx-commits mailing list