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