[libcxx-commits] [libcxx] [libc++] Refactor memory allocation in basic_string (PR #128423)
Louis Dionne via libcxx-commits
libcxx-commits at lists.llvm.org
Wed Sep 10 09:33:25 PDT 2025
================
@@ -3481,31 +3435,29 @@ inline _LIBCPP_CONSTEXPR_SINCE_CXX20 void basic_string<_CharT, _Traits, _Allocat
if (__fits_in_sso(__target_capacity)) {
__annotation_guard __g(*this);
+ auto __allocation = __get_internal_long_buffer();
__set_short_size(__size);
- traits_type::copy(std::__to_address(__get_short_pointer()), std::__to_address(__ptr), __size + 1);
- __alloc_traits::deallocate(__alloc_, __ptr, __cap);
+ traits_type::copy(std::__to_address(__get_short_pointer()), std::__to_address(__allocation.ptr), __size + 1);
+ __deallocate_long_buffer(__alloc_, __allocation);
return;
}
# if _LIBCPP_HAS_EXCEPTIONS
try {
# endif // _LIBCPP_HAS_EXCEPTIONS
__annotation_guard __g(*this);
- auto __allocation = std::__allocate_at_least(__alloc_, __target_capacity + 1);
+ auto __allocation = __allocate_long_buffer(__alloc_, size());
// The Standard mandates shrink_to_fit() does not increase the capacity.
// With equal capacity keep the existing buffer. This avoids extra work
// due to swapping the elements.
- if (__allocation.count - 1 >= capacity()) {
- __alloc_traits::deallocate(__alloc_, __allocation.ptr, __allocation.count);
+ if (__allocation.count - 1 > capacity()) {
+ __deallocate_long_buffer(__alloc_, __allocation);
return;
}
- __begin_lifetime(__allocation.ptr, __allocation.count);
- traits_type::copy(std::__to_address(__allocation.ptr), std::__to_address(__ptr), __size + 1);
- __alloc_traits::deallocate(__alloc_, __ptr, __cap);
- __set_long_cap(__allocation.count);
- __set_long_pointer(__allocation.ptr);
+ traits_type::copy(std::__to_address(__allocation.ptr), std::__to_address(__get_long_pointer()), __size + 1);
+ __replace_internal_buffer(__allocation, size());
----------------
ldionne wrote:
```suggestion
__replace_internal_buffer(__allocation, __size);
```
https://github.com/llvm/llvm-project/pull/128423
More information about the libcxx-commits
mailing list