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 }