名稱空間
變體
操作

std::allocator<T>::allocate_at_least

來自 cppreference.com
< 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
成員函式
allocator::allocate_at_least
(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不完整型別,則此函式的使用是 ill-formed 的。

目錄

[編輯] 引數

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::vectorstd::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);
 
    /* construct, use, then destroy elements */
 
    alloc.deallocate(res.ptr, res.count);
}

可能的輸出

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

[編輯] 另請參閱

記錄 allocate_at_least 分配的儲存地址和實際大小
(類模板) [編輯]
[static] (C++23)
透過分配器分配至少請求大小的儲存空間
(std::allocator_traits<Alloc> 的公共靜態成員函式) [編輯]