std::ranges::uninitialized_fill_n
来自 cppreference.cn
定义于头文件 <memory> |
||
调用签名 |
||
template< no-throw-forward-range I, class T > requires std::constructible_from<std::iter_value_t<I>, const T&> |
(自 C++20 起) (constexpr 自 C++26 起) |
|
将 value 复制到未初始化的内存区域 first +
[
0,
count)
,如同通过 return ranges::uninitialized_fill(std::counted_iterator(first, count),
std::default_sentinel, value).base();
如果在初始化期间抛出异常,则已构造的对象将以未指定的顺序销毁。
此页面上描述的类似函数的实体是算法函数对象(非正式地称为niebloid),也就是说
内容 |
[edit] 参数
first | - | 要初始化的元素范围的起始位置 |
count | - | 要构造的元素数量 |
value | - | 用于构造元素的值 |
[edit] 返回值
如上所述。
[edit] 复杂度
与 count 成线性关系。
[edit] 异常
在目标范围中构造元素时抛出的任何异常。
[edit] 注解
如果输出范围的值类型是平凡类型,则实现可以提高 ranges::uninitialized_fill_n
的效率,例如通过使用 ranges::fill_n。
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr 用于 专用内存算法 |
[edit] 可能的实现
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{}; |
[edit] 示例
运行此代码
#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
[edit] 缺陷报告
以下行为更改的缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 3870 | C++20 | 此算法可能在 const 存储上创建对象 | 保持不允许 |
[edit] 参见
(C++20) |
将对象复制到由范围定义的未初始化内存区域 (算法函数对象) |
将对象复制到由起始位置和计数定义的未初始化内存区域 (函数模板) |