Namespaces
Variants

std::ranges:: uninitialized_fill_n

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
定義先ヘッダ <memory>
呼び出しシグネチャ
template < no-throw-forward-range I, class T >

requires std:: constructible_from < std:: iter_value_t < I > , const T & >
I uninitialized_fill_n ( I first, std:: iter_difference_t < I > count,

const T & value ) ;
(C++20以降)
(constexpr C++26以降)

未初期化メモリ領域 first + [ 0 , count ) value をコピーする。以下のように動作する: return ranges:: uninitialized_fill ( std:: counted_iterator ( first, count ) ,
std:: default_sentinel , value ) . base ( ) ;

初期化中に例外がスローされた場合、既に構築されたオブジェクトは未規定の順序で破棄されます。

このページで説明されている関数ライクなエンティティは、 アルゴリズム関数オブジェクト (非公式には niebloids として知られる)です。すなわち:

目次

パラメータ

first - 要素を初期化する範囲の先頭
count - 構築する要素の数
value - 要素の構築に使用する値

戻り値

上記の通り。

計算量

count に対して線形。

例外

宛先範囲内の要素の構築中にスローされる例外。

注記

実装は、出力範囲の値型が TrivialType である場合、 ranges::fill_n を使用するなどして、 ranges::uninitialized_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 (...) // ロールバック: 構築済み要素を破棄
        {
            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++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 3870 C++20 このアルゴリズムは const ストレージ上にオブジェクトを作成する可能性がある 許可されないまま維持

関連項目

オブジェクトを範囲で定義された未初期化メモリ領域にコピーする
(アルゴリズム関数オブジェクト)
オブジェクトを開始位置とカウントで定義された未初期化メモリ領域にコピーする
(関数テンプレート)