【STL源码剖析读书笔记】自己实现简单的空间配置器MyAllocator
MyAllocator.h
#ifndef MY_ALLOCATOR_H #define MY_ALLOCATOR_H #include<new> //placement new #include<cstddef> //ptrdiff_t size_t //分配内存 template<typename T> inline T* _allocator(ptrdiff_t n,T*){ T* temp = (T*)(::operator new((size_t)(n*sizeof(T)))); if (temp == 0){ cout << "out of memory" << endl; exit(1); } return temp; } //释放内存 template<typename T> inline void _deallocator(T* ptr){ ::operator delete(ptr); } //构造对象 template<typename T,typename V> inline void _construct(T* ptr, const V& value){ new (ptr) T(value); //定位new,在指定地址处构造对象 } //析构对象 template<typename T> inline void _destroy(T* ptr){ ptr->~T(); } template<typename T> class MyAllocator{ 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 MyAllocator<U> other; }; pointer allocator(size_type n){ return _allocator((difference_type)n,(pointer)0); } void deallocator(pointer ptr){ _deallocator(ptr); } void construct(pointer ptr, value_type value){ _construct(ptr, value); } void destroy(pointer ptr){ _destroy(ptr); } pointer address(reference x){ return (pointer)&x; } const_pointer address(reference x) const{ return (const_pointer)&x; } size_type max_type() const{ return size_type(UINT_MAX / sizeof(T)); } }; #endif
main.cpp
#include "MyAllocator.h" #include<iostream> using namespace std; int main(){ MyAllocator<int> alloc; int* ptr=alloc.allocator(2); alloc.construct(ptr, 10); alloc.construct(ptr+1, 8); cout << *ptr << endl; cout << ptr[1] << endl; alloc.destroy(ptr); alloc.destroy(ptr + 1); alloc.deallocator(ptr); MyAllocator<int>::rebind<double>::other dalloc; double* p = dalloc.allocator(2); dalloc.construct(p, 3.5); cout << *p << endl; dalloc.destroy(p); dalloc.deallocator(p); system("pause"); return 0; }