std::ranges::uninitialized_default_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_default_construct(std::counted_iterator(first, count),
std::default_sentinel).base();
若在初始化期間丟擲異常,則已構造的物件將以未指定順序銷燬。
本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
first | - | 要初始化元素範圍的起始 |
count | - | 要構造的元素數量 |
[編輯] 返回值
如上所述。
[編輯] 複雜度
關於 count 的線性複雜度。
[編輯] 異常
在目標範圍內構造元素時丟擲的任何異常。
[編輯] 注意
如果預設初始化 std::iter_value_t<I> 物件時沒有呼叫非平凡的預設建構函式,則實現可以跳過物件構造(不改變可觀察效果),這可以透過 std::is_trivially_default_constructible 檢測。
[編輯] 注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | 特殊化記憶體演算法的 constexpr |
[編輯] 可能實現
struct uninitialized_default_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_default_construct(iter, std::default_sentinel).base(); } }; inline constexpr uninitialized_default_construct_n_fn uninitialized_default_construct_n{}; |
[編輯] 示例
執行此程式碼
#include <cstring> #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_default_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_default_construct_n // generally does not zero-fill the given uninitialized memory area. constexpr int sample[]{1, 2, 3, 4, 5, 6}; int v[]{1, 2, 3, 4, 5, 6}; std::ranges::uninitialized_default_construct_n(std::begin(v), std::size(v)); if (std::memcmp(v, sample, sizeof(v)) == 0) { // Maybe undefined behavior, pending CWG 1997: // for (const int i : v) { std::cout << i << ' '; } for (const int i : sample) std::cout << i << ' '; } else std::cout << "Unspecified!"; std::cout << '\n'; }
可能的輸出
1 █▓▒░ █▓▒░ 2 █▓▒░ █▓▒░ 3 █▓▒░ █▓▒░ 4 █▓▒░ █▓▒░ 1 2 3 4 5 6
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 3870 | C++20 | 此演算法可能在 const 儲存上建立物件 | 保持不允許 |
[編輯] 參閱
透過預設初始化在由範圍定義的未初始化記憶體區域中構造物件 (演算法函式物件) | |
在由範圍定義的未初始化記憶體區域中,透過值初始化構造物件 (演算法函式物件) | |
在由起始和計數定義的未初始化記憶體區域中,透過值初始化構造物件 (演算法函式物件) | |
在由起始和計數定義的未初始化記憶體區域中,透過預設初始化構造物件 (函式模板) |