◐ Shell
clean mode source ↗

std::uninitialized_fill_n - cppreference.com

来自cppreference.com

在标头 <memory> 定义

template< class NoThrowForwardIt, class Size, class T >
NoThrowForwardIt uninitialized_fill_n( NoThrowForwardIt first,
                                       Size count, const T& value );
(1) (C++26 起为 constexpr)
template< class ExecutionPolicy,
          class NoThrowForwardIt, class Size, class T >
NoThrowForwardIt uninitialized_fill_n( ExecutionPolicy&& policy,
                                       NoThrowForwardIt first,
                                       Size count, const T& value );
(2) (C++17 起)

1) 如同用以下方式以给定值 value 构造从 first 开始的目标范围中的首 count 个元素:

for (; count--; ++first)
    ::new (voidify(*first))
        typename std::iterator_traits<NoThrowForwardIt>::value_type(value);
return first;

如果初始化中抛出了异常,那么以未指定的顺序销毁已构造的对象。

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 - 要初始化的元素范围起始
count - 要构造的元素数量
value - 构造元素所用的值
类型要求
-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 Size, class T>
constexpr NoThrowForwardIt uninitialized_fill_n(NoThrowForwardIt first,
                                                Size count, const T& value)
{
    using V = typename std::iterator_traits<NoThrowForwardIt>::value_type;
    NoThrowForwardIt current = first;
    try
    {
        for (; count > 0; ++current, (void) --count)
            ::new (static_cast<void*>(std::addressof(*current))) V(value);
        return current;
    }
    catch (...)
    {
        for (; first != current; ++first)
            first->~V();
        throw;
    }
    return current;
}

示例

#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>

int main()
{
    std::string* p;
    std::size_t sz;
    std::tie(p, sz) = std::get_temporary_buffer<std::string>(4);
    std::uninitialized_fill_n(p, sz, "Example");
    
    for (std::string* i = p; i != p + sz; ++i)
    {
        std::cout << *i << '\n';
        i->~basic_string<char>();
    }
    std::return_temporary_buffer(p);
}

输出:

Example
Example
Example
Example

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 866 C++98 给定 TNoThrowForwardIt 的值类型,如果存在
T::operator new,那么程序可能会非良构
改用全局的布置 new
LWG 1339 C++98 没有返回填充范围后的首个元素的位置 返回该位置
LWG 2433 C++11 此算法可能被重载的 operator& 劫持 使用 std::addressof

参阅