std:: uninitialized_fill_n
|
定义于头文件
<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 起) |
+
[
0
,
count
)
,操作方式类似于
for
(
;
count
--
;
++
first
)
::
new
(
voidify
(
*
first
)
)
typename
std::
iterator_traits
<
NoThrowForwardIt
>
::
value_type
(
value
)
;
return
first
;
|
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 异常。
注释
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__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++ 标准。
| 缺陷报告 | 应用于 | 发布时行为 | 正确行为 |
|---|---|---|---|
| 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)
|
将对象复制到由起始点和计数定义的未初始化内存区域
(算法函数对象) |