名前空間
変種
操作

std::uninitialized_fill_n

提供: cppreference.com
< cpp‎ | memory
 
 
ユーティリティライブラリ
汎用ユーティリティ
日付と時間
関数オブジェクト
書式化ライブラリ (C++20)
(C++11)
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)
スワップと型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
一般的な語彙の型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等文字列変換
(C++17)
(C++17)
 
動的メモリ管理
スマートポインタ
(C++11)
(C++11)
(C++11)
(C++17未満)
(C++11)
アロケータ
メモリリソース
未初期化記憶域
ガベージコレクションサポート
その他
(C++20)
(C++11)
(C++11)
C のライブラリ
低水準のメモリ管理
 
ヘッダ <memory> で定義
(1)
template< class ForwardIt, class Size, class T >
void uninitialized_fill_n( ForwardIt first, Size count, const T& value );
(C++11未満)
template< class ForwardIt, class Size, class T >
ForwardIt uninitialized_fill_n( ForwardIt first, Size count, const T& value );
(C++11以上)
template< class ExecutionPolicy, class ForwardIt, class Size, class T >
ForwardIt uninitialized_fill_n( ExecutionPolicy&& policy, ForwardIt first, Size count, const T& value );
(2) (C++17以上)
1) 以下のように行われたかのように、指定された値 valuefirst から始まる未初期化メモリ領域の最初の count 個の要素にコピーします。
for (; count--; ++first)
  ::new (static_cast<void*>(std::addressof(*first)))
     typename std::iterator_traits<ForwardIt>::value_type(value);
初期化中に例外が投げられた場合、すでに構築されたオブジェクトは未規定の順序で破棄されます。
2) (1) と同じですが、 policy に従って実行されます。 このオーバーロードは、 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> が true でなければ、オーバーロード解決に参加しません。

目次

[編集] 引数

first - 初期化する要素の範囲の先頭
count - 構築する要素の数
value - 要素を構築するための値
型の要件
-
ForwardItLegacyForwardIterator の要件を満たさなければなりません。
-
ForwardIt の有効なインスタンスのインクリメント、代入、比較、間接参照は例外を投げてはなりません。

[編集] 戻り値

(なし) (C++11未満)

コピーされた最後の要素の次の要素を指すイテレータ。

(C++11以上)

[編集] 計算量

count ��比例。

[編集] 例外

テンプレート引数 ExecutionPolicy を持つオーバーロードは以下のようにエラーを報告します。

  • アルゴリズムの一部として呼び出された関数の実行が例外を投げ、 ExecutionPolicy標準のポリシーのいずれかの場合は、 std::terminate が呼ばれます。 それ以外のあらゆる ExecutionPolicy については、動作は処理系定義です。
  • アルゴリズムがメモリの確保に失敗した場合は、 std::bad_alloc が投げられます。

[編集] 実装例

template< class ForwardIt, class Size, class T >
ForwardIt uninitialized_fill_n(ForwardIt first, Size count, const T& value)
{
    typedef typename std::iterator_traits<ForwardIt>::value_type Value;
    ForwardIt current = first;
    try {
        for (; count > 0; ++current, (void) --count) {
            ::new (static_cast<void*>(std::addressof(*current))) Value(value);
        }
        return current;
    } catch (...) {
        for (; first != current; ++first) {
            first->~Value();
        }
        throw;
    }
}

[編集]

#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>
 
int main()
{
    std::string* p;
    std::size_t sz;
    std::tie(p, sz) = std::get_temporary_buffer<std::string>(4);
    std::uninitialized_fill_n(p, sz, "Example");
 
    for (std::string* i = p; i != p+sz; ++i) {
        std::cout << *i << '\n';
        i->~basic_string<char>();
    }
    std::return_temporary_buffer(p);
}

出力:

Example
Example
Example
Example

[編集] 関連項目

1個のオブジェクトをメモリの未初期化領域の指定範囲にコピーします
(関数テンプレート) [edit]