Namespaces
Variants

std::allocator<T>:: allocate_at_least

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (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)
(C++11) (until C++23)
constexpr std:: allocation_result < T * , std:: size_t >
allocate_at_least ( std:: size_t n ) ;
(自 C++23 起)

分配 count * sizeof ( T ) 字节的未初始化存储空间,其中 count 是不小于 n 的未指定整数值,通过调用 :: operator new (可能带有额外的 std::align_val_t 参数)实现,但未指定该函数的调用时机与调用方式。

随后,该函数在存储中创建一个类型为 T [ count ] 的数组并启动其生存期,但不会启动其任何元素的生存期。

为了在常量表达式中使用此函数,已分配的内存在同一表达式的求值过程中必须被释放。

T 不完整类型 ,则此函数的使用会导致编译错误。

目录

参数

n - 要为对象分配存储空间的数量下限

返回值

std:: allocation_result < T * > { p, count } ,其中 p 指向一个包含 count T 类型对象的数组的首元素,该数组中的元素尚未被构造。

异常

std:: numeric_limits < std:: size_t > :: max ( ) / sizeof ( T ) < n 时抛出 std::bad_array_new_length ,或在分配失败时抛出 std::bad_alloc

注释

allocate_at_least 主要提供给连续容器使用,例如 std::vector std::basic_string ,通过使其容量在可能时匹配实际分配的大小来减少重新分配。

“未指定时机与方式”的措辞使得标准库容器的 堆内存分配可被合并或优化消除 ,即使此类优化在直接调用 :: operator new 时不被允许。例如,libc++ 就实现了这种优化( [1] [2] )。

在调用 allocate_at_least 之后、元素构造之前, T * 的指针算术在已分配数组范围内是明确定义的,但若访问元素则行为未定义。

功能测试 标准 功能
__cpp_lib_allocate_at_least 202302L (C++23) allocate_at_least

示例

#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);
    /* 构造、使用并销毁元素 */
    alloc.deallocate(res.ptr, res.count);
}

可能的输出:

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

参见

记录由 allocate_at_least 分配的存储地址和实际大小
(类模板)
[静态] (C++23)
通过分配器分配至少达到请求大小的存储空间
( std::allocator_traits<Alloc> 的公开静态成员函数)