std::ranges::uninitialized_fill_n
来自cppreference.com
<tbody>
</tbody>
| 在标头 <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();
如果初始化中抛出了异常,那么以未指定的顺序销毁已构造的对象。
此页面上描述的函数式实体是算法函数对象(非正式地称为 niebloid),即:
参数
| 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&>
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 (...) // 回滚:销毁已构造的元素
{
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 << "异常!\n";
}
}
输出:
cppreference
cppreference
cppreference
Defect reports
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 3870 | C++20 | 此算法可能在 const 存储上创建对象
|
保持禁止 |
参阅
(C++20) |
复制一个对象到范围所定义的未初始化内存 (算法函数对象) |
| 复制一个对象到起点和数量所定义的未初始化内存 (函数模板) |