std::allocator<T>::allocate_at_least

From cppreference.com
< cpp‎ | memory‎ | allocator
Memory management library
(exposition only*)
Uninitialized memory algorithms
(C++17)
(C++17)
(C++17)
(C++20)
Constrained uninitialized
memory algorithms
(C++20)
C Library

Allocators
(C++11)
(C++11)
Memory resources
Garbage collection support
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
Uninitialized storage
(until C++20*)
(until C++20*)
(until C++20*)
Explicit lifetime management
std::allocator
Member functions
(until C++20)
allocator::allocate_at_least
(C++23)
(until C++20)
(until C++20)
(until C++20)
Non-member functions
(until C++20)
constexpr std::allocation_result <T*, std::size_t >
    allocate_at_least( std::size_t n ) ;
(since C++23)

Allocates count * sizeof(T) bytes of uninitialized storage, where count is an unspecified integer value not less than n, by calling ::operator new (possibly with an additional std::align_val_t

Then, this function creates an array of type T[count]

In order to use this function in a constant expression, the allocated storage must be deallocated within the evaluation of the same expression.

Use of this function is ill-formed if T is an incomplete type.

Parameters

n - the lower bound of number of objects to allocate storage for

Return value

std::allocation_result <T* > {p, count} , where p points to the first element of an array of count objects of type T

Exceptions

Throws std::bad_array_new_length if std::numeric_limits < std::size_t > :: max ( ) / sizeof(T) < , or std::bad_alloc

Notes

allocate_at_least is mainly provided for contiguous containers, e.g. std::vector and std::basic_string

The "unspecified when and how" wording makes it possible to combine or optimize away heap allocations made by the standard library containers, even though such optimizations are disallowed for direct calls to ::operator new. For example, this is implemented by libc++ ([1] and [2]

After calling allocate_at_least and before construction of elements, pointer arithmetic of T*

Feature-test macro Value Std Feature
__cpp_lib_allocate_at_least 202302L (C++23) allocate_at_least etc.

Example

#include <memory>
#include <print>
 
int main()
{
    const std::size_t count{69};
    std::allocator<int> alloc;
    std::allocation_result res{alloc.allocate_at_least(count)};
    std::print("count: {}\n"
               "res.ptr: {}\n"
               "res.count: {}\n", count, res.ptr, res.count);
 
    /* construct, use, then destroy elements */
 
    alloc.deallocate(res.ptr, res.count);
}

Possible output:

count: 69
res.ptr: 0x555a486a0960
res.count: 96

See also

records the address and the actual size of storage allocated by allocate_at_least
(class template)
[static] (C++23)
allocates storage at least as large as the requested size via an allocator
(public static member function of std::allocator_traits<Alloc>)