std::uninitialized_value_construct
来自 zh.cppreference.net
| 定义于头文件 <memory>
|
||
template< class NoThrowForwardIt >
void uninitialized_value_construct( NoThrowForwardIt first,
NoThrowForwardIt last );
|
(1) | (C++17 起) (C++26 起 constexpr) |
template< class ExecutionPolicy, class NoThrowForwardIt >
void uninitialized_value_construct( ExecutionPolicy&& policy,
NoThrowForwardIt first,
NoThrowForwardIt last );
|
(2) | (C++17 起) |
1) 在目标范围
[first, last) 中通过 值初始化 构造元素,如同通过
for (; first != last; ++first)
::new (voidify(*first))
typename std::iterator_traits<NoThrowForwardIt>::value_type();
如果在初始化期间抛出异常,则已构造的对象将以未指定的顺序被销毁。
2) 与 (1) 相同,但按照
policy 执行。 此重载仅当以下表达式的值为
true:
|
|
(C++20 前) |
|
|
(C++20 起) |
参数
| first, last | - | 定义待初始化元素 范围 的迭代器对 |
| policy | - | 要使用的 执行策略 |
| 类型要求 | ||
-
NoThrowForwardIt
必须满足
LegacyForwardIterator
的要求。
|
||
-
NoThrowForwardIt
有效实例进行的自增、赋值、比较或解引用操作均不得抛出异常。
|
||
异常
2) 在执行过程中:
- 如果并行化所需的临时内存资源不可用,则抛出 std::bad_alloc。
- 如果通过算法参数访问对象时抛出了未捕获的异常,则行为由执行策略决定(对于 标准策略,会调用 std::terminate)。
备注
| 功能测试宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr用于特化<memory>算法, (1)
|
可能的实现
template<class NoThrowForwardIt> constexpr void uninitialized_value_construct(NoThrowForwardIt first, NoThrowForwardIt last) { using Value = typename std::iterator_traits<NoThrowForwardIt>::value_type; NoThrowForwardIt current = first; try { for (; current != last; ++current) { ::new (static_cast<void*>(std::addressof(*current))) Value(); } } catch (...) { std::destroy(first, current); throw; } } |
示例
运行此代码
#include <iostream> #include <memory> #include <string> int main() { struct S { std::string m{"Default value"}; }; constexpr int n{3}; alignas(alignof(S)) unsigned char mem[n * sizeof(S)]; try { auto first{reinterpret_cast<S*>(mem)}; auto last{first + n}; std::uninitialized_value_construct(first, last); for (auto it{first}; it != last; ++it) std::cout << it->m << '\n'; std::destroy(first, last); } catch (...) { std::cout << "Exception!\n"; } // 对于标量类型,uninitialized_value_construct // 会将给定的未初始化内存区域零填充。 int v[]{1, 2, 3, 4}; for (const int i : v) std::cout << i << ' '; std::cout << '\n'; std::uninitialized_value_construct(std::begin(v), std::end(v)); for (const int i : v) std::cout << i << ' '; std::cout << '\n'; }
输出:
Default value Default value Default value 1 2 3 4 0 0 0 0
参见
|
(C++17)
|
在由起始位置和数量定义的未初始化内存区域中通过
值初始化
构造对象
(函数模板) |
|
(C++17)
|
在由范围定义的未初始化内存区域中通过
默认初始化
构造对象
(函数模板) |
|
在由范围定义的未初始化内存区域中通过
值初始化
构造对象
(算法函数对象) |