debug_allocator.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043 #ifndef _DEBUG_ALLOCATOR_H
00044 #define _DEBUG_ALLOCATOR_H 1
00045
00046 #include <stdexcept>
00047
00048 _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)
00049
00050 using std::size_t;
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060 template<typename _Alloc>
00061 class debug_allocator
00062 {
00063 public:
00064 typedef typename _Alloc::size_type size_type;
00065 typedef typename _Alloc::difference_type difference_type;
00066 typedef typename _Alloc::pointer pointer;
00067 typedef typename _Alloc::const_pointer const_pointer;
00068 typedef typename _Alloc::reference reference;
00069 typedef typename _Alloc::const_reference const_reference;
00070 typedef typename _Alloc::value_type value_type;
00071
00072 private:
00073
00074
00075 size_type _M_extra;
00076
00077 _Alloc _M_allocator;
00078
00079 public:
00080 debug_allocator()
00081 {
00082 const size_t __obj_size = sizeof(value_type);
00083 _M_extra = (sizeof(size_type) + __obj_size - 1) / __obj_size;
00084 }
00085
00086 pointer
00087 allocate(size_type __n)
00088 {
00089 pointer __res = _M_allocator.allocate(__n + _M_extra);
00090 size_type* __ps = reinterpret_cast<size_type*>(__res);
00091 *__ps = __n;
00092 return __res + _M_extra;
00093 }
00094
00095 pointer
00096 allocate(size_type __n, const void* __hint)
00097 {
00098 pointer __res = _M_allocator.allocate(__n + _M_extra, __hint);
00099 size_type* __ps = reinterpret_cast<size_type*>(__res);
00100 *__ps = __n;
00101 return __res + _M_extra;
00102 }
00103
00104 void
00105 deallocate(pointer __p, size_type __n)
00106 {
00107 if (__p)
00108 {
00109 pointer __real_p = __p - _M_extra;
00110 if (*reinterpret_cast<size_type*>(__real_p) != __n)
00111 {
00112 throw std::runtime_error("debug_allocator::deallocate"
00113 " wrong size");
00114 }
00115 _M_allocator.deallocate(__real_p, __n + _M_extra);
00116 }
00117 else
00118 throw std::runtime_error("debug_allocator::deallocate null pointer");
00119 }
00120 };
00121
00122 _GLIBCXX_END_NAMESPACE
00123
00124 #endif