std::uninitialized_fill

定义于头文件 <memory>
template< class ForwardIt, class T >
void uninitialized_fill( ForwardIt first, ForwardIt last, const T& value );
(1)
template< class ExecutionPolicy, class ForwardIt, class T >
void uninitialized_fill( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, const T& value );
(2) (C++17 起)
1) 复制给定的 value 到以 [first, last) 定义的未初始化内存区域,如同用
for (; first != last; ++first)
  ::new (static_cast<void*>(std::addressof(*first)))
      typename std::iterator_traits<ForwardIt>::value_type(x);
若初始化期间抛异常,则函数无效果。
2)(1) ,但按照 policy 执行。此重载不参与重载决议,除非 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 为 true 。

目录

参数

first, last - 要初始化的元素的范围
value - 构造元素所用的值
policy - 所用的执行策略。细节见执行策略
类型要求
-
ForwardIt 必须满足 ForwardIterator 的要求。
-
通过 ForwardIt 合法实例的自增、赋值、比较或间接均不可抛异常。

返回值

(无)

复杂度

firstlast 间的距离成线性

异常

拥有名为 ExecutionPolicy 的模板参数的重载按下列方式报告错误:

可能的实现

template<class ForwardIt, class T>
void uninitialized_fill(ForwardIt first, ForwardIt last, const T& value)
{
    typedef typename std::iterator_traits<ForwardIt>::value_type Value;
    ForwardIt current = first;
    try {
        for (; current != last; ++current) {
            ::new (static_cast<void*>(std::addressof(*current))) Value(value);
        }
    }  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(p, 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

参阅

复制一个对象到以起点和计数定义的未初始化内存区域
(函数模板)

版本历史

  • (当前 | 先前 2017年9月12日 (二) 06:32Fruderica讨论 | 贡献. . (2,585字节) (+719). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 17:57P12bot讨论 | 贡献 . . (1,866字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:07P12bot讨论 | 贡献 . . (1,866字节) (-77). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 14:28P12bot讨论 | 贡献 . . (1,943字节) (+297). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 03:41P12讨论 | 贡献 . . (1,646字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,646字节) (-65). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:55P12讨论 | 贡献 . . (1,711字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,711字节) (+1,711). . (Translated from the English version using Google Translate)