Namespaces
Variants

std::uninitialized_fill

来自 zh.cppreference.net
 
 
算法库
受约束算法和范围上的算法 (C++20)
受约束算法,例如ranges::copy, ranges::sort, ...
排序及相关操作
划分操作
(C++11)    

排序操作
二分搜索操作
(在划分好的范围上)
集合操作(在有序范围上)
合并操作(在有序范围上)
堆操作
最小/最大操作
(C++11)
(C++17)
字典序比较操作
排列操作


 
 
定义于头文件 <memory>
template< class NoThrowForwardIt, class T >
void uninitialized_fill( NoThrowForwardIt first,
                         NoThrowForwardIt last, const T& value );
(1) (C++26 起 constexpr)
template< class ExecutionPolicy, class NoThrowForwardIt, class T >
void uninitialized_fill( ExecutionPolicy&& policy,
                         NoThrowForwardIt first,
                         NoThrowForwardIt last, const T& value );
(2) (C++17 起)
1) 在目标范围中构造元素 [first, last) 使用给定的值 value 如同通过

for (; first != last; ++first)
    ::new (voidify(*first))
        typename std::iterator_traits<NoThrowForwardIt>::value_type(value);

如果初始化期间抛出异常,则已构造的对象将以未指定的顺序被销毁。
2) 同 (1) ,但根据 policy。
只有当以下表达式的值为 true:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(C++20 前)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(C++20 起)

参数

first, last - 定义待初始化元素 范围 的迭代器对
value - 用于构造元素的值
policy - 使用的 执行策略
类型要求
-
NoThrowForwardIt 必须满足 LegacyForwardIterator 的要求
-
对 NoThrowForwardIt 有效实例进行递增、赋值、比较或解引用操作均不得抛出异常 。对 NoThrowForwardIt 值应用 & * 必须得到指向其值类型的指针 (C++11 前)

异常

2) 在执行过程中:
  • 如果并行化所需的临时内存资源不可用,std::bad_alloc 被抛出。
  • 如果在通过算法参数访问对象时抛出未捕获的异常,则由执行策略决定行为(对于标准策略,会调用std::terminate)。

注解

功能测试宏 值 标准 功能
__cpp_lib_raw_memory_algorithms 202411L (C++26) constexpr用于特化<memory>算法, (1)

可能的实现

template<class NoThrowForwardIt, class T>
constexpr void uninitialized_fill(NoThrowForwardIt first, NoThrowForwardIt last,
                                  const T& value)
{
    using V = typename std::iterator_traits<NoThrowForwardIt>::value_type;
    NoThrowForwardIt current = first;
    try
    {
        for (; current != last; ++current)
            ::new (static_cast<void*>(std::addressof(*current))) V(value);
    } 
    catch (...)
    {
        for (; first != current; ++first)
            first->~V();
        throw;
    }
}

示例

#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
int main()
{
    const std::size_t sz = 4;
    std::allocator<std::string> alloc;
    std::string* p = alloc.allocate(sz);
    std::uninitialized_fill(p, p + sz, "Example");
    for (std::string* i = p; i != p + sz; ++i)
    {
        std::cout << *i << '\n';
        i->~basic_string<char>();
    }
    alloc.deallocate(p, sz);
}

输出:

Example
Example
Example
Example

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
LWG 866 C++98 将 T 作为 NoThrowForwardIt 的值类型,若
T::operator new 存在,则程序可能为非良构。
改用全局布置 new
LWG 2433 C++11 此算法可能被重载的 operator& 劫持;使用 std::addressof

参见

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