[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
Thu Dec 19 18:39:48 PST 2024


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

>From 3fb8884d92d39da26ad19b4f069f436e2cc9c16a 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 525fc35b26cc9e..7d9a8a0eb2f16e 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