blob: 4d3426b612a53b5b459dcc010ee8fa2990df2304 [file] [log] [blame]
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00001#ifndef STACK_ALLOCATOR_H
2#define STACK_ALLOCATOR_H
3
4#include <cstddef>
5#include <new>
6
7template <class T, std::size_t N>
8class stack_allocator
9{
10 char buf_[sizeof(T)*N];
11 char* ptr_;
12public:
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
25private:
26 stack_allocator(const stack_allocator&);// = delete;
27 stack_allocator& operator=(const stack_allocator&);// = delete;
28
29public:
30 pointer allocate(size_type n, const void* = 0)
31 {
32 if (n > N - (ptr_ - buf_) / sizeof(value_type))
33 throw std::bad_alloc();
34 pointer r = (T*)ptr_;
35 ptr_ += n * sizeof(T);
36 return r;
37 }
38 void deallocate(pointer p, size_type n)
39 {
40 if ((char*)(p + n) == ptr_)
41 ptr_ = (char*)p;
42 }
43
44 size_type max_size() const {return N;}
45};
46
47template <class T, std::size_t N>
48inline
49void
50swap(stack_allocator<T, N>& x, stack_allocator<T, N>& y) {}
51
52#endif