std:: uninitialized_fill
|
定义于头文件
<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 起) |
[
first
,
last
)
,其实现方式类似于:
for
(
;
first
!
=
last
;
++
first
)
::
new
(
voidify
(
*
first
)
)
typename
std::
iterator_traits
<
NoThrowForwardIt
>
::
value_type
(
value
)
;
|
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)
|
将对象复制到由范围定义的未初始化内存区域
(算法函数对象) |