MyAllocator.h
#ifndef MY_ALLOCATOR_H#define MY_ALLOCATOR_H#include//placement new#include //ptrdiff_t size_t//分配内存template 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 inline void _deallocator(T* ptr){ ::operator delete(ptr);}//构造对象template inline void _construct(T* ptr, const V& value){ new (ptr) T(value); //定位new,在指定地址处构造对象}//析构对象template inline void _destroy(T* ptr){ ptr->~T();}template 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 struct rebind{ typedef MyAllocator 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"#includeusing namespace std;int main(){ MyAllocator 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 ::rebind ::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;}