Allocator的简易实现

我们只需改动allocate和deallocate,来实现自己的内存分配策略即可。

代码如下:

 1 #ifndef ALLOCATOR_H
 2 #define ALLOCATOR_H 
 3 
 4 #include <stddef.h>
 5 #include <limits>
 6 
 7 template <typename T>
 8 class Allocator
 9 {
10 public:
11     typedef size_t      size_type;
12     typedef ptrdiff_t   difference_type;
13     typedef T*          pointer;
14     typedef const T*    const_pointer;
15     typedef T&          reference;
16     typedef const T&    const_reference;
17     typedef T           value_type;
18 
19     template <typename V>
20     struct rebind
21     {
22         typedef Allocator<V> other;
23     };
24 
25     pointer address(reference value) const { return &value; }
26     const_pointer address(const_reference value) const { return &value; }
27 
28     Allocator() throw() { }
29     Allocator(const Allocator &v) throw() { }
30     template <typename V>
31     Allocator(const Allocator<V> &v) { } 
32 
33     ~Allocator() throw() { }
34 
35     size_type max_size() const throw()
36     { return std::numeric_limits<size_type>::max() / sizeof(T); }
37 
38     pointer allocate(size_type num)
39     { return (pointer)(::operator new(num * sizeof(T))); }
40 
41     void construct(pointer p, const T &value)
42     { new((void*)p) T(value); }
43 
44     void destroy(pointer p)
45     { p->~T(); }
46 
47 
48     void deallocate(pointer p, size_type num)
49     { ::operator delete((void*)p); }
50 
51 };
52 
53 
54 template <typename T, typename V>
55 bool operator==(const Allocator<T> &a, const Allocator<V> &b)
56 { return true; }
57 
58 
59 template <typename T, typename V>
60 bool operator!=(const Allocator<T> &a, const Allocator<V> &b)
61 { return false; }
62 #endif /*ALLOCATOR_H*/


测试代码如下:

 1 #include "alloc.hpp"
 2 #include <string>
 3 #include <vector>
 4 using namespace std;
 5 
 6 
 7 int main(int argc, char const *argv[])
 8 {
 9     vector<string, Allocator<string> > vec(10, "haha");
10 
11     vec.push_back("foo");
12     vec.push_back("bar");
13 
14     //Allocator<Test>::rebind<Test2>::other alloc;
15 
16     return 0;
17 }

 

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值