std::allocator即空间配置器,用于内存分配。更多的细节建议大家研究相关源码。
这里仅是利用std::allocator来实现简单的自定义vector类,如有问题欢迎指正。
1 #include <iostream> 2 #include <memory> 3 using std::cout; 4 using std::endl; 5 6 template <typename Tp> 7 class Vector 8 { 9 public: 10 Vector() 11 : _elems(NULL) 12 , _first_free(NULL) 13 , _end(NULL) 14 {} 15 16 ~Vector() 17 { 18 if(_elems) 19 { 20 while(_elems != _first_free) 21 _alloc.destroy(--_first_free); 22 _alloc.deallocate(_elems,capacity()); 23 } 24 } 25 26 void push_back(const Tp & value) 27 { 28 if(size() == capacity()) 29 { 30 reallocate(); 31 } 32 _alloc.construct(_first_free++,value); 33 } 34 35 void pop_back() 36 { 37 if(size() > 0) 38 { 39 _alloc.destory(--_first_free); 40 } 41 } 42 43 size_t size() const 44 { 45 return _first_free - _elems; 46 } 47 size_t capacity() const 48 { 49 return _end - _elems; 50 } 51 52 Tp & operator[](size_t idx) 53 { 54 return _elems[idx]; 55 } 56 57 private: 58 void reallocate() 59 { 60 size_t oldCapacity = capacity(); 61 size_t newCapacity = oldCapacity == 0 ? 1 : oldCapacity * 2; 62 63 Tp * newElems = _alloc.allocate(newCapacity); 64 if(_elems) 65 { 66 std::uninitialized_copy(_elems,_first_free,newElems); 67 while(_elems != _first_free) 68 _alloc.destroy(--_first_free); 69 _alloc.deallocate(_elems,oldCapacity); 70 } 71 _elems = newElems; 72 _first_free = _elems + oldCapacity; 73 _end = _elems + newCapacity; 74 } 75 private: 76 static std::allocator<Tp> _alloc; 77 Tp * _elems; 78 Tp * _first_free; 79 Tp * _end; 80 }; 81 82 template <typename Tp> 83 std::allocator<Tp> Vector<Tp>::_alloc; 84 85 void display(Vector<int> & vec) 86 { 87 cout << "vec's size = " << vec.size() << endl; 88 cout << "vec's capacity = " << vec.capacity() << endl; 89 }
以下是测试代码:
1 int test() 2 { 3 Vector<int> vecInt; 4 display(vecInt); 5 6 vecInt.push_back(1); 7 display(vecInt); 8 vecInt.push_back(2); 9 display(vecInt); 10 vecInt.push_back(3); 11 display(vecInt); 12 vecInt.push_back(4); 13 display(vecInt); 14 vecInt.push_back(5); 15 display(vecInt); 16 vecInt.push_back(6); 17 display(vecInt); 18 vecInt.push_back(7); 19 display(vecInt); 20 21 for(size_t idx = 0; idx != vecInt.size(); ++idx) 22 { 23 cout << vecInt[idx] << " "; 24 } 25 cout << endl; 26 return 0; 27 }
测试结果:
1 vec's size = 0 2 vec's capacity = 0 3 vec's size = 1 4 vec's capacity = 1 5 vec's size = 2 6 vec's capacity = 2 7 vec's size = 3 8 vec's capacity = 4 9 vec's size = 4 10 vec's capacity = 4 11 vec's size = 5 12 vec's capacity = 8 13 vec's size = 6 14 vec's capacity = 8 15 vec's size = 7 16 vec's capacity = 8 17 1 2 3 4 5 6 7