Skip to content

Commit c7f62ec

Browse files
committed
[libc++][vector] Fixes shrink_to_fit.
This assures shrink_to_fit does not increase the allocated size. Partly addresses #95161
1 parent f90bac9 commit c7f62ec

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

libcxx/include/vector

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1443,7 +1443,11 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 void vector<_Tp, _Allocator>::shrink_to_fit() _NOE
14431443
#endif // _LIBCPP_HAS_NO_EXCEPTIONS
14441444
allocator_type& __a = this->__alloc();
14451445
__split_buffer<value_type, allocator_type&> __v(size(), size(), __a);
1446-
__swap_out_circular_buffer(__v);
1446+
// The Standard mandates shrink_to_fit() does not increase the capacity.
1447+
// With equal capacity keep the existing buffer. This avoids extra work
1448+
// due to swapping the elements.
1449+
if (__v.capacity() < capacity())
1450+
__swap_out_circular_buffer(__v);
14471451
#ifndef _LIBCPP_HAS_NO_EXCEPTIONS
14481452
} catch (...) {
14491453
}

libcxx/test/std/containers/sequences/vector/vector.capacity/shrink_to_fit.pass.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,46 @@ TEST_CONSTEXPR_CXX20 bool tests() {
7171
return true;
7272
}
7373

74+
std::size_t min_bytes = 1000;
75+
76+
template <typename T>
77+
struct increasing_allocator {
78+
using value_type = T;
79+
increasing_allocator() = default;
80+
template <typename U>
81+
increasing_allocator(const increasing_allocator<U>&) noexcept {}
82+
std::allocation_result<T*> allocate_at_least(std::size_t n) {
83+
std::size_t allocation_amount = n * sizeof(T);
84+
if (allocation_amount < min_bytes)
85+
allocation_amount = min_bytes;
86+
min_bytes += 1000;
87+
return {static_cast<T*>(::operator new(allocation_amount)), allocation_amount};
88+
}
89+
T* allocate(std::size_t n) { return allocate_at_least(n).ptr; }
90+
void deallocate(T* p, std::size_t) noexcept { ::operator delete(static_cast<void*>(p)); }
91+
};
92+
93+
template <typename T, typename U>
94+
bool operator==(increasing_allocator<T>, increasing_allocator<U>) {
95+
return true;
96+
}
97+
98+
// https://github.com/llvm/llvm-project/issues/95161
99+
void test_increasing_allocator() {
100+
std::vector<int, increasing_allocator<int>> v;
101+
v.push_back(1);
102+
assert(is_contiguous_container_asan_correct(v));
103+
std::size_t capacity = v.capacity();
104+
v.shrink_to_fit();
105+
assert(v.capacity() == capacity);
106+
assert(v.size() == 1);
107+
assert(is_contiguous_container_asan_correct(v));
108+
}
109+
74110
int main(int, char**)
75111
{
76112
tests();
113+
test_increasing_allocator();
77114
#if TEST_STD_VER > 17
78115
static_assert(tests());
79116
#endif

0 commit comments

Comments
 (0)