00001 #ifndef __LDK__STLMALLOCALLOCATOR_H__
00002 #define __LDK__STLMALLOCALLOCATOR_H__
00003
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00028
00036
00037 #include "LDK/Exceptions.h"
00038 #include "LDK/TemplateMeta.h"
00039 #include <stdlib.h>
00040 #include <assert.h>
00041
00042 namespace LDK
00043 {
00053 template<class T>
00054 class MallocAllocator
00055 {
00056 public:
00057 typedef size_t size_type;
00058 typedef ptrdiff_t difference_type;
00059 typedef T* pointer;
00060 typedef const T* const_pointer;
00061 typedef T& reference;
00062 typedef const T& const_reference;
00063 typedef T value_type;
00064
00065 template<typename T1>
00066 struct rebind
00067 {
00068 typedef MallocAllocator<T1> other;
00069 };
00070
00071 inline MallocAllocator() {}
00072 inline MallocAllocator(const MallocAllocator&) {}
00073 template<typename T1>
00074 inline MallocAllocator(const MallocAllocator<T1>&) {}
00075 inline ~MallocAllocator() {}
00076
00077 inline pointer address(reference r) const { return &r; }
00078
00079 inline const_pointer address(const_reference r) const { return &r; }
00080
00081
00082 inline pointer allocate(size_type n, const void* = 0)
00083 {
00084 pointer ret = NULL;
00085 assert(n);
00086 ret = reinterpret_cast<pointer>(malloc(n*sizeof(value_type)));
00087 if(!ret)
00088 throw LDK_BADALLOC_ERROR;
00089 return ret;
00090 }
00091
00092
00093 template <size_type n>
00094 inline pointer allocate()
00095 {
00096 pointer ret = NULL;
00097 CTASSERT(n>0,allocatorInvalidObjectCount);
00098 ret = reinterpret_cast<pointer>(malloc(n*sizeof(value_type)));
00099 if(!ret)
00100 throw LDK_BADALLOC_ERROR;
00101 return ret;
00102 }
00103
00104 inline pointer reallocate(pointer mem, size_type newNo)
00105 {
00106 assert(mem);
00107 assert(newNo);
00108 return ::realloc(mem,newNo*sizeof(value_type));
00109 }
00110
00111
00112 inline char* _Charalloc(size_type n, const void* = 0)
00113 {
00114 assert(n);
00115 char* ret = reinterpret_cast<char*>(malloc(n));
00116 if(!ret)
00117 throw LDK_BADALLOC_ERROR;
00118 return ret;
00119 }
00120
00121 inline void deallocate(void* p, size_type n)
00122 {
00123 ::free(p);
00124 }
00125
00126 inline size_type max_size() const { return size_type(-1) / sizeof(value_type); }
00127
00128 inline void construct(pointer p, const value_type& val) { new(p) value_type(val); }
00129 inline void destroy(pointer p) { p->~T(); }
00130 };
00131
00132 template<typename T1, typename T2>
00133 inline bool operator==(const MallocAllocator<T1>&, const MallocAllocator<T2>&) { return true; }
00134
00135 template<typename T1, typename T2>
00136 inline bool operator!=(const MallocAllocator<T1>&, const MallocAllocator<T2>&) { return false; }
00137
00138 }
00139
00140 #endif //__LDK__STLMALLOCALLOCATOR_H__