00001 // -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- 00002 // vi: set et ts=4 sw=2 sts=2: 00003 #ifndef DUNE_MALLOC_ALLOCATOR_HH 00004 #define DUNE_MALLOC_ALLOCATOR_HH 00005 00006 #include <exception> 00007 #include <cstdlib> 00008 #include <new> 00009 #include <utility> 00010 #include <dune/common/unused.hh> 00011 00016 namespace Dune 00017 { 00022 template <class T> 00023 class MallocAllocator { 00024 public: 00025 typedef std::size_t size_type; 00026 typedef std::ptrdiff_t difference_type; 00027 typedef T* pointer; 00028 typedef const T* const_pointer; 00029 typedef T& reference; 00030 typedef const T& const_reference; 00031 typedef T value_type; 00032 template <class U> struct rebind { 00033 typedef MallocAllocator<U> other; 00034 }; 00035 00037 MallocAllocator() throw() {} 00039 template <class U> 00040 MallocAllocator(const MallocAllocator<U>&) throw() {} 00042 ~MallocAllocator() throw() {} 00043 00044 pointer address(reference x) const 00045 { 00046 return &x; 00047 } 00048 const_pointer address(const_reference x) const 00049 { 00050 return &x; 00051 } 00052 00054 pointer allocate(size_type n, 00055 const void* hint = 0) 00056 { 00057 DUNE_UNUSED_PARAMETER(hint); 00058 if (n > this->max_size()) 00059 throw std::bad_alloc(); 00060 00061 pointer ret = static_cast<pointer>(std::malloc(n * sizeof(T))); 00062 if (!ret) 00063 throw std::bad_alloc(); 00064 return ret; 00065 } 00066 00068 void deallocate(pointer p, size_type n) 00069 { 00070 DUNE_UNUSED_PARAMETER(n); 00071 std::free(p); 00072 } 00073 00075 size_type max_size() const throw() 00076 { 00077 return size_type(-1) / sizeof(T); 00078 } 00079 00081 void construct(pointer p, const T& val) 00082 { 00083 ::new((void*)p)T(val); 00084 } 00085 00087 template<typename ... _Args> 00088 void construct(pointer p, _Args&&... __args) 00089 { 00090 ::new((void *)p)T(std::forward<_Args>(__args) ...); 00091 } 00092 00094 void destroy(pointer p) 00095 { 00096 p->~T(); 00097 } 00098 }; 00099 } 00100 00101 #endif // DUNE_MALLOC_ALLOCATOR_HH