定义于头文件
<memory>
|
||
(1) | ||
template< class ForwardIt, class Size, class T >
void uninitialized_fill_n( ForwardIt first, Size count, const T& value ); |
(C++11 前) | |
template< class ForwardIt, class Size, class T >
ForwardIt uninitialized_fill_n( ForwardIt first, Size count, const T& value ); |
(C++11 起) | |
template< class ExecutionPolicy, class ForwardIt, class Size, class T >
ForwardIt uninitialized_fill_n( ExecutionPolicy&& policy, ForwardIt first, Size count, const T& value ); |
(2) | (C++17 起) |
value
到始于 first
的未初始化内存区域的首 count
个元素,如同以
for (; n--; ++first) ::new (static_cast<void*>(std::addressof(*first))) typename std::iterator_traits<ForwardIt>::value_type(x);
policy
执行。此重载不参与重载决议,除非 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 为 true 。目录 |
first | - | 要初始化的元素范围起始 |
count | - | 要构造的元素数量 |
value | - | 构造元素所用的值 |
类型要求 | ||
-
ForwardIt 必须满足 ForwardIterator 的要求。
|
||
-
通过 ForwardIt 合法实例的自增、赋值、比较或间接均不可抛异常。
|
(无) | (C++11 前) |
指向最后复制的元素后一位置元素的迭代器。 |
(C++11 起) |
与 count
成线性。
拥有名为 ExecutionPolicy
的模板参数的重载按下列方式报告错误:
ExecutionPolicy
是三个标准策略之一,则调用 std::terminate 。对于任何其他 ExecutionPolicy
,行为是实现定义的。
template< class ForwardIt, class Size, class T > ForwardIt uninitialized_fill_n(ForwardIt first, Size count, const T& value) { typedef typename std::iterator_traits<ForwardIt>::value_type Value; ForwardIt current = first; try { for (; count > 0; ++current, (void) --count) { ::new (static_cast<void*>(std::addressof(*current))) Value(value); } return current; } catch (...) { for (; first != current; ++first) { first->~Value(); } throw; } } |
#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
复制一个对象到以范围定义的未初始化内存区域 (函数模板) |