名稱空間
變體
操作

std::allocator_traits<Alloc>::allocate_at_least

來自 cppreference.com
 
 
記憶體管理庫
(僅作說明*)
未初始化記憶體演算法
(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*)
顯式生命週期管理
 
 
static constexpr std::allocation_result<pointer, size_type>
    allocate_at_least( Alloc& a, size_type n );
(C++23 起)

allocate_at_least 呼叫 a.allocate_at_least(n),如果該呼叫格式良好,則返回其結果;否則,它等價於 return {a.allocate(n), n};

allocator_at_least 嘗試為至少 nvalue_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_least 202302L (C++23) allocate_at_least 等。

[編輯] 示例

[編輯] 參閱

分配至少與請求大小一樣大的未初始化儲存
(std::allocator<T> 的公共成員函式) [編輯]