std::ranges::uninitialized_fill_n
来自 zh.cppreference.net
| 定义于头文件 <memory>
|
||
| 调用签名 |
||
template< /*nothrow-forward-iterator*/ 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 );
|
(1) | (自C++20起) (自C++26起 constexpr) |
template< /*execution-policy*/ Ep, /*nothrow-random-access-iterator*/ I,
class T = std::iter_value_t<I> >
requires std::constructible_from<std::iter_value_t<I>, const T&>
I uninitialized_fill_n( Ep&& exec, I first, std::iter_difference_t<I> count,
const T& value );
|
(2) | (自C++26起) |
关于 /*execution-policy*/ 的定义,参见 此页面;关于其他仅用于说明的概念的定义,参见 此页面。
1) 在目标范围
first + [0, count) 中用给定值 value 构造元素,如同通过
return ranges::uninitialized_fill(std::counted_iterator(first, count),
std::default_sentinel, value).base();
如果初始化期间抛出异常,则已构造的对象将以未指定顺序销毁。
2) 与 (1) 相同,但根据
policy 执行。此页面描述的函数式实体是 算法函数对象 (非正式地称为 niebloids), 即:
参数
| first | - | 要初始化的元素范围的起始 |
| count | - | 要构造的元素数量 |
| value | - | 用于构造元素的值 |
| policy | - | 要使用的execution policy |
返回值
如上所述。
异常
在目标范围内构造元素时抛出的任何异常.
2) 在执行过程中:
- 如果并行化所需的临时内存资源不可用, std::bad_alloc则抛出.
- 如果在通过算法参数访问对象时抛出了未捕获的异常, 则行为由执行策略决定(对于标准策略, std::terminate会被调用).
注解
实现可能提高ranges::uninitialized_fill_n的效率(例如通过使用ranges::fill_n),如果输出范围的值类型是TrivialType。
| 功能测试宏 | 值 | 标准 | 特性 |
|---|---|---|---|
__cpp_lib_parallel_algorithm |
202506L |
(C++26) | 并行范围算法 |
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr 用于 特化 <memory> 算法, (1)
|
可能的实现
struct uninitialized_fill_n_fn
{
template</*nothrow-forward-range*/ I, class T>
requires std::constructible_from<std::iter_value_t<I>, const T&>
constexpr I operator()(I first, std::iter_difference_t<I> count,
const T& value) const
{
I rollback{first};
try
{
for (; count-- > 0; ++first)
ranges::construct_at(std::addressof(*first), value);
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++20) |
将一个对象复制到由范围定义的内存未初始化区域 (算法函数对象) |
| 将一个对象复制到由起始位置和计数定义的内存未初始化区域 (函数模板) |