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