命名空间
变体
操作

std::ranges::uninitialized_fill_n

来自 cppreference.cn
< cpp‎ | 内存
 
 
内存管理库
(仅作说明*)
未初始化内存算法
(C++17)
(C++17)
(C++17)
受约束的未初始化
内存算法
ranges::uninitialized_fill_n
(C++20)
C 库

分配器
内存资源
垃圾回收支持
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化存储
(直到 C++20*)
(直到 C++20*)
显式生命周期管理
 
定义于头文件 <memory>
调用签名 (Call signature)
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 + [0count),如同通过 return ranges::uninitialized_fill(std::counted_iterator(first, count),
                                  std::default_sentinel, value).base();

若在初始化期间抛出异常,则已构造的对象将以未指定顺序销毁。

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

目录

[编辑] 参数

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

[编辑] 返回值

如上所述。

[编辑] 复杂度

关于 count 的线性复杂度。

[编辑] 异常

在目标范围内构造元素时抛出的任何异常。

[编辑] 注意

如果输出范围的值类型是TrivialType,则实现可以提高 ranges::uninitialized_fill_n 的效率,例如通过使用 ranges::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 (...) // rollback: destroy constructed elements
        {
            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++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 3870 C++20 此算法可能在 const 存储上创建对象 保持不允许

[编辑] 参阅

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