跳到主要内容

std::allocator_traits<Alloc>::allocate_at_least

自 C++23 起
[[nodiscard]] static constexpr std::allocation_result< pointer, size_type >
allocate_at_least( Alloc& a, size_type n );

allocate_at_least 调用 a.allocate_at_least(n) 并返回其结果(如果调用格式正确),否则,它等效于 return {a.allocate(n), n};

allocator_at_least 尝试为至少 n 个 value_type 对象分配存储空间,并提供一个备用机制,该机制为正好 n 个对象分配存储空间。

参数

a - 用于分配存储的分配器
n - 要为其分配存储对象的最小数量

返回值

如果格式正确,则为 a.allocate_at_least(n)

否则,为 std::allocation_result<pointer, size_type>{a.allocate(n), n}

异常

抛出选定的分配函数抛出的内容和时间。

备注

Allocator 类型的 allocate_at_least 成员函数主要为连续容器提供,例如 std::vectorstd::basic_string,以便在可能的情况下通过使它们的容量与实际分配的大小匹配来减少重新分配。由于 allocate_at_least 提供了备用机制,因此可以在适当的地方直接使用它。

给定类型为 Alloc 的分配器对象 a,设 result 表示从 std::allocator_traits<Alloc>::allocate_at_least(a, n) 返回的值,存储应通过 a.deallocate(result.ptr, m)(通常通过 std::allocator_traits<Alloc>::deallocate(a, result.ptr, m) 调用)来解除分配,以避免内存泄漏。

解除分配中使用的参数 m 必须不小于 n 且不大于 result.count,否则行为未定义。请注意,如果分配器不提供 allocate_at_least,则 n 始终等于 result.count,这意味着要求 m 等于 n

特性测试宏标准注释
__cpp_lib_allocate_at_least202302L(C++23)allocate_at_least 等

示例

本节不完整

std::allocator_traits<Alloc>::allocate_at_least

自 C++23 起
[[nodiscard]] static constexpr std::allocation_result< pointer, size_type >
allocate_at_least( Alloc& a, size_type n );

allocate_at_least 调用 a.allocate_at_least(n) 并返回其结果(如果调用格式正确),否则,它等效于 return {a.allocate(n), n};

allocator_at_least 尝试为至少 n 个 value_type 对象分配存储空间,并提供一个备用机制,该机制为正好 n 个对象分配存储空间。

参数

a - 用于分配存储的分配器
n - 要为其分配存储对象的最小数量

返回值

如果格式正确,则为 a.allocate_at_least(n)

否则,为 std::allocation_result<pointer, size_type>{a.allocate(n), n}

异常

抛出选定的分配函数抛出的内容和时间。

备注

Allocator 类型的 allocate_at_least 成员函数主要为连续容器提供,例如 std::vectorstd::basic_string,以便在可能的情况下通过使它们的容量与实际分配的大小匹配来减少重新分配。由于 allocate_at_least 提供了备用机制,因此可以在适当的地方直接使用它。

给定类型为 Alloc 的分配器对象 a,设 result 表示从 std::allocator_traits<Alloc>::allocate_at_least(a, n) 返回的值,存储应通过 a.deallocate(result.ptr, m)(通常通过 std::allocator_traits<Alloc>::deallocate(a, result.ptr, m) 调用)来解除分配,以避免内存泄漏。

解除分配中使用的参数 m 必须不小于 n 且不大于 result.count,否则行为未定义。请注意,如果分配器不提供 allocate_at_least,则 n 始终等于 result.count,这意味着要求 m 等于 n

特性测试宏标准注释
__cpp_lib_allocate_at_least202302L(C++23)allocate_at_least 等

示例

本节不完整