std::uninitialized_default_construct
来自 zh.cppreference.net
| 定义于头文件 <memory>
|
||
template< class NoThrowForwardIt >
void uninitialized_default_construct( NoThrowForwardIt first,
NoThrowForwardIt last );
|
(1) | (自 C++17 起) (C++26 起为 constexpr) |
template< class ExecutionPolicy, class NoThrowForwardIt >
void uninitialized_default_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) 相同,但根据
policypolicy. 执行。该重载仅当以下表达式的值为
truetrue|
|
(直到 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_default_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 <cstring> #include <iostream> #include <memory> #include <string> struct S { std::string m{"Default value"}; }; int main() { 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_default_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_default_construct // 通常不会对给定的未初始化内存区域进行零填充。 int v[]{1, 2, 3, 4}; const int original[]{1, 2, 3, 4}; std::uninitialized_default_construct(std::begin(v), std::end(v)); // 可能是未定义行为,等待 CWG 1997 决议。 // for (const int i : v) // std::cout << i << ' '; // 结果未指定。 std::cout << (std::memcmp(v, original, sizeof(v)) == 0 ? "Unmodified\n" : "Modified\n"); }
可能的输出:
Default value Default value Default value Unmodified
参见
|
通过
默认初始化
在由起始位置和数量定义的未初始化内存区域中构造对象
(函数模板) |
|
|
(C++17)
|
通过
值初始化
在由范围定义的未初始化内存区域中构造对象
(函数模板) |
|
通过
默认初始化
在由范围定义的未初始化内存区域中构造对象
(算法函数对象) |