std::ranges::uninitialized_fill_n
来自cppreference.com
在标头 <memory> 定义
|
||
调用签名 |
||
template< no-throw-forward-range I, class T > requires std::constructible_from<std::iter_value_t<I>, const T&> |
(C++20 起) | |
在范围 [
first,
first + n)
所指代的未初始化内存区域构造给定值 x 的 n 个副本,如同用
for (; n--; ++first) { ::new (static_cast<void*>(std::addressof(*first))) std::remove_reference_t<std::iter_reference_t<I>>(x); }
若初始化期间抛出异常,则以未指定顺序销毁已构造的对象。
此页面上描述的函数式实体是 niebloid,即:
实践中,可以作为函数对象,或者用某些特殊编译器扩展实现它们。
参数
first | - | 要初始化的元素范围的起始 |
n | - | 构造的元素数 |
x | - | 用以构造元素的值 |
返回值
等于 first + n 的迭代器。
复杂度
与 n 成线性。
异常
构造目标范围中的元素时抛出的异常,若存在。
注解
若输出范围的值类型为平凡类型 (TrivialType) ,则实现可能提升 ranges::uninitialized_fill_n
的效率,例如用 ranges::fill_n。
可能的实现
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 (...) // 回滚:销毁已构造的元素 { 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
Defect reports
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 3870 | C++20 | 此算法可能在 const 存储上创建对象 | 保持禁止 |
参阅
(C++20) |
复制一个对象到范围所定义的未初始化的内存区域 (niebloid) |
复制一个对象到以起点和计数定义的未初始化内存区域 (函数模板) |