std::ranges::uninitialized_value_construct_n
來自 cppreference.com
| 定義於標頭檔案 <memory> |
||
| 呼叫簽名 (Call signature) |
||
template< no-throw-forward-iterator I > requires std::default_initializable<std::iter_value_t<I>> |
(C++20 起) (C++26 起為 constexpr) |
|
在未初始化的記憶體區域 first + [0, count) 中,透過值初始化構造型別為 std::iter_value_t<I> 的物件,如同透過 return ranges::uninitialized_value_construct(std::counted_iterator(first, count),
std::default_sentinel).base();
若在初始化期間丟擲異常,則已構造的物件將以未指定順序銷燬。
本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
| first | - | 要初始化元素範圍的起始 |
| count | - | 要構造的元素數量 |
[編輯] 返回值
如上所述。
[編輯] 複雜度
關於 count 的線性複雜度。
[編輯] 異常
在目標範圍內構造元素時丟擲的任何異常。
[編輯] 注意
如果範圍的值型別是CopyAssignable的TrivialType,則實現可以提高 ranges::uninitialized_value_construct_n 的效率,例如透過使用ranges::fill_n。
| 特性測試宏 | 值 | 標準 | 特性 |
|---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | 特殊化記憶體演算法的 constexpr |
[編輯] 可能實現
struct uninitialized_value_construct_n_fn { template<no-throw-forward-iterator I> requires std::default_initializable<std::iter_value_t<I>> constexpr I operator()(I first, std::iter_difference_t<I> count) const { auto iter = std::counted_iterator(first, count); return ranges::uninitialized_value_construct(iter, std::default_sentinel).base(); } }; inline constexpr uninitialized_value_construct_n_fn uninitialized_value_construct_n{}; |
[編輯] 示例
執行此程式碼
#include <iostream> #include <memory> #include <string> int main() { struct S { std::string m{"█▓▒░ █▓▒░ █▓▒░ "}; }; constexpr int n{4}; alignas(alignof(S)) char out[n * sizeof(S)]; try { auto first{reinterpret_cast<S*>(out)}; auto last = std::ranges::uninitialized_value_construct_n(first, n); auto count{1}; for (auto it{first}; it != last; ++it) std::cout << count++ << ' ' << it->m << '\n'; std::ranges::destroy(first, last); } catch (...) { std::cout << "Exception!\n"; } // For scalar types, uninitialized_value_construct_n // zero-initializes the given uninitialized memory area. int v[]{1, 2, 3, 4, 5, 6, 7, 8}; std::cout << ' '; for (const int i : v) std::cout << i << ' '; std::cout << "\n "; std::ranges::uninitialized_value_construct_n(std::begin(v), std::size(v)); for (const int i : v) std::cout << i << ' '; std::cout << '\n'; }
輸出
1 █▓▒░ █▓▒░ █▓▒░ 2 █▓▒░ █▓▒░ █▓▒░ 3 █▓▒░ █▓▒░ █▓▒░ 4 █▓▒░ █▓▒░ █▓▒░ 1 2 3 4 5 6 7 8 0 0 0 0 0 0 0 0
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
| 缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
|---|---|---|---|
| LWG 3870 | C++20 | 此演算法可能在 const 儲存上建立物件 | 保持不允許 |
[編輯] 參閱
| 在由範圍定義的未初始化記憶體區域中,透過值初始化構造物件 (演算法函式物件) | |
| 透過預設初始化在由範圍定義的未初始化記憶體區域中構造物件 (演算法函式物件) | |
| 透過預設初始化在由起始和計數定義的未初始化記憶體區域中構造物件 (演算法函式物件) | |
| 在由起始和計數定義的未初始化記憶體區域中,透過值初始化構造物件 (函式模板) |