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 起)
(C++26 起为 constexpr)

value 复制到未初始化内存区域 first + [ 0 , count ) ,其效果相当于执行 return ranges:: uninitialized_fill ( std:: counted_iterator ( first, count ) ,
std:: default_sentinel , value ) . base ( ) ;

如果在初始化过程中抛出异常,已构造的对象将以未指定的顺序被销毁。

本页面描述的函数式实体是 算法函数对象 (非正式称为 niebloids ),即:

目录

参数

first - 要初始化的元素范围的起始位置
count - 要构造的元素数量
value - 用于构造元素的值

返回值

如上所述。

复杂度

count 上呈线性关系。

异常

在目标范围元素构造过程中抛出的任何异常。

注释

当输出范围的 值类型 为平凡类型时,实现可通过使用 ranges::fill_n 等方式提升 ranges::uninitialized_fill_n 的执行效率。

功能测试 标准 功能特性
__cpp_lib_raw_memory_algorithms 202411L (C++26) constexpr for 专用内存算法

可能的实现

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 存储上创建对象 保持禁止状态

参见

将对象复制到由范围定义的未初始化内存区域
(算法函数对象)
将对象复制到由起始位置和计数定义的未初始化内存区域
(函数模板)