CARMA C++
MpAllocator.h
1 #ifndef CARMA_UTIL_MP_ALLOCATOR_H
2 #define CARMA_UTIL_MP_ALLOCATOR_H
3 
4 #include <limits>
5 #include <cstdlib>
6 
7 
8 namespace carma {
9 namespace util {
10 
11 
12 class MpRawAllocator {
13  public:
14  static void * alloc( ::std::size_t bytes );
15  static void dealloc( void * p, ::std::size_t bytes );
16 };
17 
18 
19 template < typename T >
20 class MpAllocator {
21  public:
22  // type definitions
23  typedef T value_type;
24  typedef T * pointer;
25  typedef const T * const_pointer;
26  typedef T& reference;
27  typedef const T & const_reference;
28  typedef ::std::size_t size_type;
29  typedef ::std::ptrdiff_t difference_type;
30 
31  // rebind allocator to type U
32  template < typename U >
33  struct rebind {
34  typedef MpAllocator< U > other;
35  };
36 
37  // return address of values
38  pointer address( reference value ) const {
39  return &value;
40  }
41 
42  const_pointer address( const_reference value ) const {
43  return &value;
44  }
45 
46  /* constructors and destructor
47  * - nothing to do because the allocator has no state
48  */
49  MpAllocator( ) throw( ) { }
50 
51  MpAllocator( const MpAllocator & rhs ) throw( ) { }
52 
53  template < typename U >
54  MpAllocator( const MpAllocator< U > & rhs ) throw( ) { }
55 
56  ~MpAllocator( ) throw( ) { }
57 
58  // return maximum number of elements that can be allocated
59  size_type max_size ( ) const throw( ) {
60  return (::std::numeric_limits< ::std::size_t >::max( ) / sizeof( T ));
61  }
62 
63  // allocate but don't initialize num elements of type T
64  pointer allocate( size_type num,
65  const void * dummy = 0 ) {
66  return static_cast< pointer >( MpRawAllocator::alloc( num * sizeof( T ) ) );
67  }
68 
69  // initialize elements of allocated storage p with value value
70  void construct( pointer p,
71  const T & value ) {
72  // initialize memory with placement new
73  new (static_cast< void * >( p )) T( value );
74  }
75 
76  // destroy elements of initialized storage p
77  void destroy( pointer p ) {
78  // destroy objects by calling their destructor
79  p->~T( );
80  }
81 
82  // deallocate storage p of deleted elements
83  void deallocate( pointer p,
84  size_type num ) {
85  MpRawAllocator::dealloc( static_cast< void * >( p ), (num * sizeof( T )) );
86  }
87 };
88 
89 
90 // return that all specializations of this allocator are interchangeable
91 
92 template < typename T1, typename T2 >
93 bool
94 operator==( const MpAllocator< T1 > & lhs, const MpAllocator< T2 > & rhs ) throw( ) {
95  return true;
96 }
97 
98 
99 template < typename T1, typename T2 >
100 bool
101 operator!=( const MpAllocator< T1 > & lhs, const MpAllocator< T2 > & rhs ) throw( ) {
102  return false;
103 }
104 
105 
106 } // namespace carma::util
107 } // namespace carma
108 
109 #endif