std:: uninitialized_fill
|
ヘッダーで定義
<memory>
|
||
|
template
<
class
NoThrowForwardIt,
class
T
>
void
uninitialized_fill
(
NoThrowForwardIt first,
|
(1) | (constexpr since C++26) |
|
template
<
class
ExecutionPolicy,
class
NoThrowForwardIt,
class
T
>
void
uninitialized_fill
(
ExecutionPolicy
&&
policy,
|
(2) | (since C++17) |
[
first
,
last
)
に
value
をコピーする。以下のように動作する:
for
(
;
first
!
=
last
;
++
first
)
::
new
(
voidify
(
*
first
)
)
typename
std::
iterator_traits
<
NoThrowForwardIt
>
::
value_type
(
value
)
;
|
std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> が true であること。 |
(C++20まで) |
|
std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> が true であること。 |
(C++20以降) |
目次 |
パラメータ
| first, last | - | 初期化する要素の 範囲 を定義するイテレータのペア |
| value | - | 要素を構築するための値 |
| policy | - | 使用する 実行ポリシー |
| 型要件 | ||
-
NoThrowForwardIt
は
LegacyForwardIterator
の要件を満たさなければならない。
|
||
-
NoThrowForwardIt
の有効なインスタンスを通じたインクリメント、代入、比較、間接参照は例外をスローしてはならない。
NoThrowForwardIt
値に
&
*
を適用すると、その値型へのポインタが得られなければならない。
(C++11まで)
|
||
計算量
first と last の間の距離に対して線形。
例外
ExecutionPolicy
という名前のテンプレートパラメータを持つオーバーロードは、
以下のようにエラーを報告します:
-
アルゴリズムの一部として呼び出された関数の実行が例外をスローした場合、
ExecutionPolicyが 標準ポリシー のいずれかであるとき、 std::terminate が呼び出される。その他のExecutionPolicyについては、動作は実装定義である。 - アルゴリズムがメモリの確保に失敗した場合、 std::bad_alloc がスローされる。
注記
| 機能テスト マクロ | 値 | 標準 | 機能 |
|---|---|---|---|
__cpp_lib_raw_memory_algorithms
|
202411L
|
(C++26) | constexpr 対応の 特殊化メモリアルゴリズム , ( 1 ) |
実装例
template<class NoThrowForwardIt, class T> constexpr void uninitialized_fill(NoThrowForwardIt first, NoThrowForwardIt last, const T& value) { using V = typename std::iterator_traits<NoThrowForwardIt>::value_type; NoThrowForwardIt current = first; try { for (; current != last; ++current) ::new (static_cast<void*>(std::addressof(*current))) V(value); } catch (...) { for (; first != current; ++first) first->~V(); throw; } } |
例
#include <algorithm> #include <iostream> #include <memory> #include <string> int main() { const std::size_t sz = 4; std::allocator<std::string> alloc; std::string* p = alloc.allocate(sz); std::uninitialized_fill(p, p + sz, "Example"); for (std::string* i = p; i != p + sz; ++i) { std::cout << *i << '\n'; i->~basic_string<char>(); } alloc.deallocate(p, sz); }
出力:
Example Example Example Example
欠陥報告
以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。
| DR | 適用対象 | 公開時の動作 | 正しい動作 |
|---|---|---|---|
| LWG 866 | C++98 |
NoThrowForwardIt
の値型を
T
とした場合、
T :: operator new が存在すると、プログラムが不適格となる可能性がある |
代わりにグローバル配置 new を使用 |
| LWG 2433 | C++11 | このアルゴリズムはオーバーロードされた operator & によってハイジャックされる可能性がある | std::addressof を使用 |
| LWG 3870 | C++20 | このアルゴリズムは const ストレージ上にオブジェクトを作成する可能性がある | 禁止されたまま維持 |
関連項目
|
オブジェクトを初期化されていないメモリ領域にコピーする(開始位置とカウントで定義)
(関数テンプレート) |
|
|
(C++20)
|
オブジェクトを初期化されていないメモリ領域にコピーする(範囲で定義)
(アルゴリズム関数オブジェクト) |