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