std::allocator<T>::allocate_at_least
来自cppreference.com
constexpr std::allocation_result<T*, std::size_t> allocate_at_least( std::size_t n ); |
(C++23 起) | |
调用 ::operator new(可能带有额外的 std::align_val_t 实参)分配 count * sizeof(T) 字节的未初始化存储,其中 count
是未指定的不小于 n 的整数值,但未指定何时及如何调用此函数。
然后,此函数在该存储中创建一个 T[count] 数组并开始其生存期,但不开始其任何元素的生存期。
为在常量表达式中使用此函数,必须在同一表达式的求值内解分配其所分配的存储。
若 T
为不完整类型则此函数的使用为非良构。
参数
n | - | 要分配存储的对象数的下界 |
返回值
std::allocation_result<T*>{p, count},其中 p
指向 T
类型的 count
个对象的数组首元素的指针,数组元素尚未构造。
异常
若 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
参阅
(C++23) |
记录由 allocate_at_least 分配的存储的地址与实际大小 (类模板) |
[静态] (C++23) |
经由分配器分配至少与请求的大小一样大的存储 ( std::allocator_traits<Alloc> 的公开静态成员函数) |