std::uninitialized_fill_n
来自 cppreference.cn
定义于头文件 <memory> |
||
template< class NoThrowForwardIt, class Size, class T > NoThrowForwardIt uninitialized_fill_n( NoThrowForwardIt first, |
(1) | (C++26 起为 constexpr) |
template< class ExecutionPolicy, class NoThrowForwardIt, class Size, class T > |
(2) | (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 起) |
目录 |
[edit] 参数
first | - | 要初始化元素范围的起始 |
count | - | 要构造的元素数量 |
value | - | 用于构造元素的值 |
类型要求 | ||
-NoThrowForwardIt 必须满足 LegacyForwardIterator 的要求。 | ||
-对 NoThrowForwardIt 的有效实例,其增量、赋值、比较或间接引用操作不得抛出异常。 对 NoThrowForwardIt 值应用 &* 必须产生指向其值类型的指针。(C++11 前) |
[edit] 返回值
如上所述。
[edit] 复杂度
关于 count 的线性复杂度。
[edit] 异常
带有名为 ExecutionPolicy
的模板参数的重载会按如下方式报告错误:
- 若作为算法一部分调用的函数执行时抛出异常且
ExecutionPolicy
为标准策略之一,则调用 std::terminate。对于任何其他ExecutionPolicy
,行为由实现定义。 - 如果算法未能分配内存,则抛出 std::bad_alloc。
[edit] 注意
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_lib_raw_memory_algorithms |
202411L |
(C++26) | constexpr 对于未初始化内存算法,(1) |
[edit] 可能的实现
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; } |
[edit] 示例
运行此代码
#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
[edit] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 866 | C++98 | 给定 T 为 NoThrowForwardIt 的值类型,如果T::operator new 存在,程序可能格式错误 |
改用全局 placement new |
LWG 1339 | C++98 | 未返回填充范围后第一个元素的位置 已返回 |
已返回 |
LWG 2433 | C++11 | 此算法可能被重载的 operator& 劫持 | 使用 std::addressof |
LWG 3870 | C++20 | 此算法可能在 const 存储上创建对象 | 保持不允许 |
[edit] 参阅
将对象复制到由范围定义的未初始化内存区域 (函数模板) | |
(C++20) |
将对象复制到由起始和计数定义的未初始化内存区域 (算法函数对象) |