std::ranges::uninitialized_value_construct_n
来自cppreference.com
| 在标头 <memory> 定义
|
||
| 调用签名 |
||
| (1) | (C++20 起) (C++26 起为 constexpr) |
|
| |
(2) | (C++26 起) |
/*execution-policy*/ 的定义见此页;其他仅用于阐述的概念的定义见此页。
1) 如同用以下方式通过值初始化构造目标范围
first + [0, count) 中的元素:
return ranges::uninitialized_value_construct(std::counted_iterator(first, count),
std::default_sentinel).base();
如果初始化中抛出了异常,那么以未指定的顺序销毁已构造的对象。
2) 同 (1),但按照
policy 执行。此页面上描述的函数式实体是算法函数对象(非正式地称为 niebloid),即:
参数
| first | - | 要初始化的元素范围的起始 |
| count | - | 要构造的元素数 |
| policy | - | 所用的执行策略 |
返回值
如上所述。
异常
构造目标范围中的元素时抛出的任何异常。
2) 在执行过程中:
- 如果并行化所需的临时内存资源不可用,那么就会抛出 std::bad_alloc。
- 如果在通过算法实参访问对象时抛出了未捕获的异常,那么行为由执行策略决定(标准策略会调用 std::terminate)。
注解
如果范围的值类型是可复制赋值 (CopyAssignable) 的平凡类型 (TrivialType) ,那么实现可以提升 ranges::uninitialized_value_construct_n 的效率(例如用 ranges::fill_n)。
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_parallel_algorithm |
202506L |
(C++26) | 并行范围算法 |
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr 的 <memory> 专门算法, (1)
|
可能的实现
struct uninitialized_value_construct_n_fn
{
template</*nothrow-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 << "异常!\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
参阅
| 在范围所定义的未初始化内存中用值初始化构造对象 (算法函数对象) | |
| 在范围所定义的未初始化内存中用默认初始化构造对象 (算法函数对象) | |
| 在起点和数量所定义的未初始化内存中用默认初始化构造对象 (算法函数对象) | |
| 在起点和数量所定义的未初始化内存中用值初始化构造对象 (函数模板) |