std::ranges:: uninitialized_value_construct_n
|
定义于头文件
<memory>
|
||
|
调用签名
|
||
|
template
<
no-throw-forward-iterator
I
>
requires
std::
default_initializable
<
std::
iter_value_t
<
I
>>
|
(C++20 起)
(C++26 起为 constexpr) |
|
在未初始化内存区域
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 上呈线性关系。
异常
在目标范围元素构造过程中抛出的任何异常。
注释
若范围的
值类型
为
可复制赋值
的
平凡类型
,实现可通过诸如使用
ranges::fill_n
等方式提升
ranges::uninitialized_value_construct_n
的执行效率。
| 功能测试 宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_raw_memory_algorithms
|
202411L
|
(C++26) | constexpr for 专用内存算法 |
可能的实现
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"; } // 对于标量类型,uninitialized_value_construct_n // 会将给定的未初始化内存区域进行零初始化。 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 存储上创建对象 | 保持禁止状态 |
参阅
|
在由范围定义的未初始化内存区域中通过
值初始化
构造对象
(算法函数对象) |
|
|
在由范围定义的未初始化内存区域中通过
默认初始化
构造对象
(算法函数对象) |
|
|
在由起始点和计数定义的未初始化内存区域中通过
默认初始化
构造对象
(算法函数对象) |
|
|
(C++17)
|
在由起始点和计数定义的未初始化内存区域中通过
值初始化
构造对象
(函数模板) |