1 #ifndef STACK_ALLOCATOR_H 2 #define STACK_ALLOCATOR_H 3 4 #include <cstddef> 5 #include <new> 6 7 template <class T, std::size_t N> 8 class stack_allocator 9 { 10 char buf_[sizeof(T)*N]; 11 char* ptr_; 12 public: 13 typedef T value_type; 14 typedef value_type* pointer; 15 typedef const value_type* const_pointer; 16 typedef value_type& reference; 17 typedef const value_type& const_reference; 18 typedef std::size_t size_type; 19 typedef std::ptrdiff_t difference_type; 20 21 template <class U> struct rebind {typedef stack_allocator<U, N> other;}; 22 23 stack_allocator() : ptr_(buf_) {} 24 25 private: 26 stack_allocator(const stack_allocator&);// = delete; 27 stack_allocator& operator=(const stack_allocator&);// = delete; 28 29 public: 30 pointer allocate(size_type n, const void* = 0) 31 { 32 if (n > N - (ptr_ - buf_) / sizeof(value_type)) { 33 #ifndef _LIBCPP_NO_EXCEPTIONS 34 throw std::bad_alloc(); 35 #else 36 std::terminate(); 37 #endif 38 } 39 pointer r = (T*)ptr_; 40 ptr_ += n * sizeof(T); 41 return r; 42 } 43 void deallocate(pointer p, size_type n) 44 { 45 if ((char*)(p + n) == ptr_) 46 ptr_ = (char*)p; 47 } 48 49 size_type max_size() const {return N;} 50 }; 51 52 template <class T, std::size_t N> 53 inline 54 void 55 swap(stack_allocator<T, N>& x, stack_allocator<T, N>& y) {} 56 57 #endif // STACK_ALLOCATOR_H 58