zoukankan      html  css  js  c++  java
  • Allocator中uninitialized_fill等函数的简单实现

    下面提供三个函数的实现代码,这三个代码的共同点是:

    1.遇到错误,抛出异常

    2.出现异常时,把之前构造的对象全部销毁

    所以,这三个函数要么成功,要么无任何副作用。使用异常来通知使用者,所以在catch块中,处理完异常后要将异常再次向外抛出

    代码如下:

     1 #ifndef UNINIT_H
     2 #define UNINIT_H
     3 #include <iterator>
     4 
     5 template <typename ForwIter, typename T>
     6 void uninitialized_fill(ForwIter first, ForwIter last, const T &value)
     7 {
     8     typedef typename std::iterator_traits<ForwIter>::value_type VT;
     9     ForwIter save(first);
    10     try
    11     {
    12         for( ; first != end; ++ first)
    13             new(static_cast<void *>(&*first))VT(value);
    14     }
    15 
    16     catch(...)
    17     {
    18         for( ; save != first; ++ save)
    19             save->~VT();
    20         throw();
    21     }
    22 }
    23 
    24 template <typename ForwIter, typename Size, typename T>
    25 void uninitialized_fill_n(ForwIter first, Size n, const T &value)
    26 {
    27     typedef typename std::iterator_traits<ForwIter>::value_type VT;
    28     ForwIter save(first);
    29     try
    30     {
    31         for( ; -- n; ++ first)
    32             new(static_cast<void *>(&*first))VT(value);
    33     }
    34     catch(...)
    35     {
    36         for( ; save != first; ++ save)
    37             save->~VT();
    38         throw();
    39     }
    40 
    41 }
    42 
    43 template <typename InputIter, typename ForwIter>
    44 void uninitialized_copy(InputIter first, InputIter last; ForwIter dest)
    45 {
    46     typedef typename std::iterator_traits<ForwIter>::value_type VT;
    47     ForwIter save(dest);
    48     try
    49     {
    50         for( ; first != last; ++ first, ++ dest)
    51             new(static_cast<void *>(&*dest))VT(*first);
    52     }
    53     catch(...)
    54     {
    55         for( ; save != dest; ++ save)
    56             save->~VT();
    57         throw();
    58     }
    59 
    60 }
    61 
    62 #endif

    可以用前面的代码自行测试。

  • 相关阅读:
    socket使用大全
    UIImageView控件使用(转)
    多线程,socket,http,asihttpRequest,等总结集合
    ios 如何判断字符串含有中文字符?
    修改UISearchBar
    abc222_e Red and Blue Tree(树上差分+01背包)
    2020icpc上海部分题解
    abc215_e Chain Contestant(状压dp)
    bzoj3238 差异(后缀数组+单调栈)
    NCD2019部分题解
  • 原文地址:https://www.cnblogs.com/gjn135120/p/4007237.html
Copyright © 2011-2022 走看看