std::ranges::uninitialized_default_construct_n
来自 cppreference.cn
定义于头文件 <memory> |
||
调用签名 (Call signature) |
||
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_default_construct(std::counted_iterator(first, count),
std::default_sentinel).base();
若在初始化期间抛出异常,则已构造的对象将以未指定顺序销毁。
本页描述的类函数实体是 算法函数对象(非正式地称为 niebloids),即
目录 |
[编辑] 参数
first | - | 要初始化元素范围的起始 |
count | - | 要构造的元素数量 |
[编辑] 返回值
如上所述。
[编辑] 复杂度
关于 count 的线性复杂度。
[编辑] 异常
在目标范围内构造元素时抛出的任何异常。
[编辑] 注意
如果默认初始化 std::iter_value_t<I> 对象时没有调用非平凡的默认构造函数,则实现可以跳过对象构造(不改变可观察效果),这可以通过 std::is_trivially_default_constructible 检测。
[编辑] 注意
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | 特殊化内存算法的 constexpr |
[编辑] 可能实现
struct uninitialized_default_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_default_construct(iter, std::default_sentinel).base(); } }; inline constexpr uninitialized_default_construct_n_fn uninitialized_default_construct_n{}; |
[编辑] 示例
运行此代码
#include <cstring> #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_default_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_default_construct_n // generally does not zero-fill the given uninitialized memory area. constexpr int sample[]{1, 2, 3, 4, 5, 6}; int v[]{1, 2, 3, 4, 5, 6}; std::ranges::uninitialized_default_construct_n(std::begin(v), std::size(v)); if (std::memcmp(v, sample, sizeof(v)) == 0) { // Maybe undefined behavior, pending CWG 1997: // for (const int i : v) { std::cout << i << ' '; } for (const int i : sample) std::cout << i << ' '; } else std::cout << "Unspecified!"; std::cout << '\n'; }
可能的输出
1 █▓▒░ █▓▒░ 2 █▓▒░ █▓▒░ 3 █▓▒░ █▓▒░ 4 █▓▒░ █▓▒░ 1 2 3 4 5 6
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 3870 | C++20 | 此算法可能在 const 存储上创建对象 | 保持不允许 |
[编辑] 参阅
通过默认初始化在由范围定义的未初始化内存区域中构造对象 (算法函数对象) | |
在由范围定义的未初始化内存区域中,通过值初始化构造对象 (算法函数对象) | |
在由起始和计数定义的未初始化内存区域中,通过值初始化构造对象 (算法函数对象) | |
在由起始和计数定义的未初始化内存区域中,通过默认初始化构造对象 (函数模板) |