《STL源码剖析》之配置自己简单的allocator

来源:互联网 发布:阿里云 ads 架构 编辑:程序博客网 时间:2024/05/17 08:42

侯先生不由分说,给了个自己的配置器实现,我也不管3721地手动跟着码代码,本来不想写那么多的蛋疼,但是编译编不过,STL内部还是有限制,好!

//#include <new>#include <cstddef>#include <cstdlib>#include <climits>#include <iostream>#include <memory>#include <vector>using namespace std;namespace Allen{template <class T>inline T* _allocate(ptrdiff_t size,void* hint = 0){set_new_handler(0);T* tmp = (T*)(malloc(size * sizeof(T)));if (NULL == tmp){cout << "out of memory\n";exit(1);}return tmp;}template <class T>inline void _deallocate(T* buffer){free(buffer);} template <class T1, class T2>inline void _construct(T1* p, const T2& value){new(p) T1(value);}template <class T>inline void _destory(T* ptr){ptr->~T();}template <class T>class allocator{public:typedef T value_type;typedef T* pointer;typedef const T* const_pointer;typedef T& reference;typedef const T& const_reference;typedef size_t size_type;typedef ptrdiff_t difference_type;template <class U>struct rebind{typedef allocator<U> other;};pointer allocate(size_type n, const void* hint = 0){return _allocate<T>(n, 0);}void deallocate(pointer p, size_t n){_deallocate(p);}void construct(pointer p, const_reference value){_construct(p, value);}void destroy(pointer p){return _destory(p);}pointer address(reference x){return &x;}const_pointer const_address(const_reference x){return &x;}size_t max_size()const{return UINT_MAX / sizeof(T);}};}int main(){int arr[5] = {0, 1, 2, 3, 4};unsigned int i = 0;vector<int, Allen::allocator<int> > vec(arr, arr+4);for (size_t i = 0; i < vec.size(); ++i){printf("%d ", vec[i]);}printf("\n");}

不过我还是有改动,看到的童鞋还是实现自己的吧,请叫我Allen,哈哈。


0 0
原创粉丝点击