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

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

转载于:https://www.cnblogs.com/gjn135120/p/4007237.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值