std::uninitialized_fill
来自cppreference.com
在标头 <memory> 定义
|
||
template< class NoThrowForwardIt, class T > void uninitialized_fill( NoThrowForwardIt first, |
(1) | (C++26 起为 constexpr) |
template< class ExecutionPolicy, class NoThrowForwardIt, class T > void uninitialized_fill( ExecutionPolicy&& policy, |
(2) | (C++17 起) |
1) 如同用以下方式将 value 复制到未初始化内存区域
[
first,
last)
:
for (; first != last; ++first)
::new (voidify
(*first))
typename std::iterator_traits<NoThrowForwardIt>::value_type(value);
如果初始化中抛出了异常,那么以未指定的顺序销毁已构造的对象。
2) 同 (1),但按照 policy 执行。
此重载只有在满足以下所有条件时才会参与重载决议:
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 是 true。 |
(C++20 前) |
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> 是 true。 |
(C++20 起) |
目录 |
[编辑] 参数
first, last | - | 要初始化的元素范围的迭代器对 |
value | - | 构造元素所用的值 |
policy | - | 所用的执行策略 |
类型要求 | ||
-NoThrowForwardIt 必须满足老式向前迭代器 (LegacyForwardIterator) 。
| ||
-通过 NoThrowForwardIt 合法实例的自增、赋值、比较或间接均不可抛异常。将 &* 应用到 NoThrowForwardIt 值的情况下必须产生指向它的值类型的指针。(C++11 前)
|
[编辑] 复杂度
与 first 和 last 间的距离成线性。
[编辑] 异常
拥有名为 ExecutionPolicy
的模板形参的重载按下列方式报告错误:
- 如果作为算法一部分调用的函数的执行抛出异常,且
ExecutionPolicy
是标准策略之一,那么调用 std::terminate。对于任何其他ExecutionPolicy
,行为由实现定义。 - 如果算法无法分配内存,那么抛出 std::bad_alloc。
[编辑] 注解
功能特性测试宏 | 值 | 标准 | 功能特性 |
---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr 的特化内存算法, (1) |
[编辑] 可能的实现
template<class NoThrowForwardIt, class T> constexpr void uninitialized_fill(NoThrowForwardIt first, NoThrowForwardIt last, const T& value) { using V = typename std::iterator_traits<NoThrowForwardIt>::value_type; NoThrowForwardIt current = first; try { for (; current != last; ++current) ::new (static_cast<void*>(std::addressof(*current))) V(value); } catch (...) { for (; first != current; ++first) first->~V(); throw; } } |
[编辑] 示例
运行此代码
#include <algorithm> #include <iostream> #include <memory> #include <string> int main() { const std::size_t sz = 4; std::allocator<std::string> alloc; std::string* p = alloc.allocate(sz); std::uninitialized_fill(p, p + sz, "Example"); for (std::string* i = p; i != p + sz; ++i) { std::cout << *i << '\n'; i->~basic_string<char>(); } alloc.deallocate(p, sz); }
输出:
Example Example Example Example
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 866 | C++98 | 给定 T 为 NoThrowForwardIt 的值类型,如果存在T::operator new,那么程序可能会非良构 |
改用全局的布置 new |
LWG 2433 | C++11 | 此算法可能被重载的 operator& 劫持 | 使用 std::addressof |
LWG 3870 | C++20 | 此算法可能在 const 存储上创建对象 | 保持不允许 |
[编辑] 参阅
复制一个对象到起点和数量所定义的未初始化内存 (函数模板) | |
(C++20) |
复制一个对象到范围所定义的未初始化内存 (算法函数对象) |