最終更新日時(UTC):
が更新

履歴 編集

function template
<memory>

std::ranges::uninitialized_fill_n(C++20)

namespace std::ranges {
  template <no-throw-forward-iterator I, class T>
    requires constructible_from<iter_value_t<I>, const T&>
  I
    uninitialized_fill_n(I first,
                         iter_difference_t<I> n,
                         const T& x);            // (1) C++20
  template <no-throw-forward-iterator I, class T>
    requires constructible_from<iter_value_t<I>, const T&>
  constexpr I
    uninitialized_fill_n(I first,
                         iter_difference_t<I> n,
                         const T& x);            // (1) C++26

  template <execution-policy Ep,
            random_access_iterator I, class T>
    requires constructible_from<iter_value_t<I>, const T&>
  I
    uninitialized_fill_n(Ep&& exec,
                         I first,
                         iter_difference_t<I> n,
                         const T& x);            // (2) C++26
}

概要

未初期化領域の範囲 ([first, first + n)) を、指定された値で配置newで初期化する。

  • (1): イテレータ範囲を指定する
  • (2): (1)の並列アルゴリズム版。実行ポリシーを指定する

テンプレートパラメータ制約

効果

以下と等価である:

例外

呼び出すコンストラクタなどから例外が送出された場合、その例外がこの関数の外側に伝播される前に、その時点で構築済のオブジェクトは全て未規定の順序で破棄される。すなわち、例外が送出された場合は初期化対象領域は未初期化のままとなる。

基本的な使い方

#include <iostream>
#include <memory>
#include <algorithm>

int main()
{
  std::allocator<int> alloc;

  // メモリ確保。
  // この段階では、[p, p + size)の領域は未初期化
  const std::size_t size = 3;
  int* p = alloc.allocate(size);

  // 未初期化領域[p, p + size)を初期化しつつ、値2で埋める
  std::ranges::uninitialized_fill_n(p, size, 2);

  // pの領域が初期化され、かつ範囲pの全ての要素が2で埋められているか確認
  std::for_each(p, p + size, [](int x) {
    std::cout << x << std::endl;
  });

  // 要素を破棄
  std::ranges::destroy_n(p, size);

  // メモリ解放
  alloc.deallocate(p, size);
}

出力

2
2
2

並列アルゴリズムの例 (C++26)

#include <iostream>
#include <memory>
#include <execution>

int main() {
  std::allocator<int> alloc;
  int* p = alloc.allocate(3);

  // 並列にn個の未初期化領域を99で埋める
  std::ranges::uninitialized_fill_n(
    std::execution::par, p, 3, 99);

  for (int i = 0; i < 3; ++i) {
    std::cout << p[i] << ' ';
  }
  std::cout << std::endl;

  alloc.deallocate(p, 3);
}

出力

99 99 99

バージョン

言語

  • C++20

処理系

関連項目

参照