命名空间
变体
操作

std::allocator<T>::allocate_at_least

来自 cppreference.cn
< cpp‎ | memory‎ | allocator
 
 
内存管理库
(仅为说明目的*)
未初始化内存算法
(C++17)
(C++17)
(C++17)
受约束的未初始化
内存算法
C 库

分配器
内存资源
垃圾回收支持
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化存储
(直到 C++20*)
(直到 C++20*)
显式生命周期管理
 
std::allocator
成员函数
(直到 C++20)
allocator::allocate_at_least
(C++23)
(直到 C++20)
(直到 C++20)
(直到 C++20)
非成员函数
(直到 C++20)
 
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不完整类型,则使用此函数是病式的。

目录

[edit] 参数

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

[edit] 返回值

std::allocation_result<T*>{p, count},其中 p 指向类型为 Tcount 个对象的数组的第一个元素,这些对象的元素尚未构造。

[edit] 异常

如果 std::numeric_limits<std::size_t>::max() / sizeof(T) < n,则抛出 std::bad_array_new_length,或者如果分配失败,则抛出 std::bad_alloc

[edit] 注意

allocate_at_least 主要为连续容器提供,例如 std::vectorstd::basic_string,以便通过使其容量与实际分配的大小尽可能匹配来减少重新分配。

“何时以及如何未指定”的措辞使得组合或优化掉堆分配成为可能,这些堆分配由标准库容器进行,即使对于直接调用 ::operator new,这种优化也是不允许的。 例如,libc++ 实现了这一点([1][2])。

在调用 allocate_at_least 之后和元素构造之前,T* 的指针算术在分配的数组中是明确定义的,但如果访问元素,则行为未定义。

特性测试 Std 特性
__cpp_lib_allocate_at_least 202302L (C++23) allocate_at_least 等。

[edit] 示例

#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);
}

可能的输出

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

[edit] 参见

记录 allocate_at_least 分配的存储的地址和实际大小
(类模板) [编辑]
[静态] (C++23)
通过分配器分配至少与请求大小一样大的存储
(std::allocator_traits<Alloc> 的公共静态成员函数) [编辑]