std::ranges::uninitialized_value_construct_n
来自 cppreference.cn
定义于头文件 <memory> |
||
调用签名 |
||
template< no-throw-forward-iterator I > requires std::default_initializable<std::iter_value_t<I>> |
(自 C++20 起) (constexpr 自 C++26 起) |
|
在未初始化的内存区域 first +
[
0,
count)
中构造类型为 std::iter_value_t<I> 的对象,通过值初始化,如同通过 return ranges::uninitialized_value_construct(std::counted_iterator(first, count),
std::default_sentinel).base();
如果在初始化期间抛出异常,则已构造的对象将以未指定的顺序销毁。
此页面上描述的类似函数的实体是算法函数对象(非正式地称为 niebloids),即
目录 |
[编辑] 参数
first | - | 要初始化的元素范围的起始位置 |
count | - | 要构造的元素数量 |
[编辑] 返回值
如上所述。
[编辑] 复杂度
与 count 成线性关系。
[编辑] 异常
在目标范围内构造元素时抛出的任何异常。
[编辑] 注解
如果范围的值类型是 CopyAssignable TrivialType,则实现可以提高 ranges::uninitialized_value_construct_n
的效率,例如通过使用 ranges::fill_n。
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr 用于 专用内存算法 |
[编辑] 可能的实现
struct uninitialized_value_construct_n_fn { template<no-throw-forward-iterator I> requires std::default_initializable<std::iter_value_t<I>> constexpr I operator()(I first, std::iter_difference_t<I> count) const { auto iter = std::counted_iterator(first, count); return ranges::uninitialized_value_construct(iter, std::default_sentinel).base(); } }; inline constexpr uninitialized_value_construct_n_fn uninitialized_value_construct_n{}; |
[编辑] 示例
运行此代码
#include <iostream> #include <memory> #include <string> int main() { struct S { std::string m{"█▓▒░ █▓▒░ █▓▒░ "}; }; constexpr int n{4}; alignas(alignof(S)) char out[n * sizeof(S)]; try { auto first{reinterpret_cast<S*>(out)}; auto last = std::ranges::uninitialized_value_construct_n(first, n); auto count{1}; for (auto it{first}; it != last; ++it) std::cout << count++ << ' ' << it->m << '\n'; std::ranges::destroy(first, last); } catch (...) { std::cout << "Exception!\n"; } // For scalar types, uninitialized_value_construct_n // zero-initializes the given uninitialized memory area. int v[]{1, 2, 3, 4, 5, 6, 7, 8}; std::cout << ' '; for (const int i : v) std::cout << i << ' '; std::cout << "\n "; std::ranges::uninitialized_value_construct_n(std::begin(v), std::size(v)); for (const int i : v) std::cout << i << ' '; std::cout << '\n'; }
输出
1 █▓▒░ █▓▒░ █▓▒░ 2 █▓▒░ █▓▒░ █▓▒░ 3 █▓▒░ █▓▒░ █▓▒░ 4 █▓▒░ █▓▒░ █▓▒░ 1 2 3 4 5 6 7 8 0 0 0 0 0 0 0 0
[编辑] 缺陷报告
以下行为更改的缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 3870 | C++20 | 此算法可能在 const 存储上创建对象 | 保持不允许 |
[编辑] 参见
在由范围定义的未初始化的内存区域中,通过值初始化构造对象 (算法函数对象) | |
在由范围定义的未初始化的内存区域中,通过默认初始化构造对象 (算法函数对象) | |
在由起始位置和计数定义的未初始化的内存区域中,通过默认初始化构造对象 (算法函数对象) | |
在由起始位置和计数定义的未初始化的内存区域中,通过值初始化构造对象 (函数模板) |