Skip to content

Commit 8dae17b

Browse files
authored
[libc++] Refactor memory allocation in basic_string (#128423)
This patch introduces a string-internal API to make the allocation and deallocation the long string simpler. Before this we had a lot of code duplication, so ensuring that things were actually correct was non-trivial.
1 parent 4dc0513 commit 8dae17b

File tree

3 files changed

+138
-203
lines changed

3 files changed

+138
-203
lines changed

libcxx/include/__memory/allocate_at_least.h

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,26 +19,31 @@
1919

2020
_LIBCPP_BEGIN_NAMESPACE_STD
2121

22+
template <class _Pointer, class _SizeT = size_t>
23+
struct __allocation_result {
24+
_Pointer ptr;
25+
_SizeT count;
26+
27+
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR __allocation_result(_Pointer __ptr, _SizeT __count)
28+
: ptr(__ptr), count(__count) {}
29+
};
30+
_LIBCPP_CTAD_SUPPORTED_FOR_TYPE(__allocation_result);
31+
2232
#if _LIBCPP_STD_VER >= 23
2333

2434
template <class _Alloc>
2535
[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto __allocate_at_least(_Alloc& __alloc, size_t __n) {
26-
return std::allocator_traits<_Alloc>::allocate_at_least(__alloc, __n);
36+
auto __res = std::allocator_traits<_Alloc>::allocate_at_least(__alloc, __n);
37+
return __allocation_result{__res.ptr, __res.count};
2738
}
2839

2940
#else
3041

31-
template <class _Pointer>
32-
struct __allocation_result {
33-
_Pointer ptr;
34-
size_t count;
35-
};
36-
37-
template <class _Alloc>
42+
template <class _Alloc, class _Traits = allocator_traits<_Alloc> >
3843
[[__nodiscard__]] _LIBCPP_HIDE_FROM_ABI
39-
_LIBCPP_CONSTEXPR __allocation_result<typename allocator_traits<_Alloc>::pointer>
44+
_LIBCPP_CONSTEXPR __allocation_result<typename _Traits::pointer, typename _Traits::size_type>
4045
__allocate_at_least(_Alloc& __alloc, size_t __n) {
41-
return {__alloc.allocate(__n), __n};
46+
return __allocation_result<typename _Traits::pointer, typename _Traits::size_type>(__alloc.allocate(__n), __n);
4247
}
4348

4449
#endif // _LIBCPP_STD_VER >= 23

0 commit comments

Comments
 (0)