std::uninitialized_fill_n
来自 cppreference.cn
定义于头文件 <memory> |
||
template< class NoThrowForwardIt, class Size, class T > NoThrowForwardIt uninitialized_fill_n( NoThrowForwardIt first, |
(1) | (constexpr since C++26) |
template< class ExecutionPolicy, class NoThrowForwardIt, class Size, class T > |
(2) | (since C++17) |
1) 将 value 复制到未初始化的内存区域 first
+
[
0,
count)
,如同通过
for (; count--; ++first)
::new (voidify
(*first))
typename std::iterator_traits<NoThrowForwardIt>::value_type(value);
return first;
如果在初始化期间抛出异常,则已构造的对象将以未指定的顺序销毁。
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 | - | 要初始化的元素范围的开始 |
count | - | 要构造的元素数量 |
value | - | 用于构造元素的值 |
类型要求 | ||
-NoThrowForwardIt 必须满足 LegacyForwardIterator 的要求。 | ||
-通过 NoThrowForwardIt 的有效实例进行的递增、赋值、比较或间接引用都不得抛出异常。 将 &* 应用于 NoThrowForwardIt 值必须产生指向其值类型的指针。(直到 C++11) |
[编辑] 返回值
如上所述。
[编辑] 复杂度
与 count 成线性关系。
[编辑] 异常
带有名为 ExecutionPolicy
的模板参数的重载按如下方式报告错误
- 如果作为算法一部分调用的函数的执行抛出异常,并且
ExecutionPolicy
是 标准策略 之一,则调用 std::terminate。 对于任何其他ExecutionPolicy
,行为是实现定义的。 - 如果算法无法分配内存,则抛出 std::bad_alloc。
[编辑] 注释
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr 用于 专用内存算法,(1) |
[编辑] 可能的实现
template<class NoThrowForwardIt, class Size, class T> constexpr NoThrowForwardIt uninitialized_fill_n(NoThrowForwardIt first, Size count, const T& value) { using V = typename std::iterator_traits<NoThrowForwardIt>::value_type; NoThrowForwardIt current = first; try { for (; count > 0; ++current, (void) --count) ::new (static_cast<void*>(std::addressof(*current))) V(value); return current; } catch (...) { for (; first != current; ++first) first->~V(); throw; } return current; } |
[编辑] 示例
运行此代码
#include <algorithm> #include <iostream> #include <memory> #include <string> #include <tuple> int main() { std::string* p; std::size_t sz; std::tie(p, sz) = std::get_temporary_buffer<std::string>(4); std::uninitialized_fill_n(p, sz, "Example"); for (std::string* i = p; i != p + sz; ++i) { std::cout << *i << '\n'; i->~basic_string<char>(); } std::return_temporary_buffer(p); }
输出
Example Example Example Example
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 866 | C++98 | 给定 T 作为 NoThrowForwardIt 的值类型,如果T::operator new 存在,程序可能是非良构的 |
使用全局放置 new 代替 |
LWG 1339 | C++98 | 第一个元素的位置,紧随 填充范围之后,未被返回 |
已返回 |
LWG 2433 | C++11 | 此算法可能被重载的 operator& 劫持 | 使用 std::addressof |
LWG 3870 | C++20 | 此算法可能在 const 存储上创建对象 | 保持不允许 |
[编辑] 参见
将对象复制到由范围定义的未初始化内存区域 (函数模板) | |
(C++20) |
将对象复制到由起始位置和计数定义的未初始化内存区域 (算法函数对象) |