| 1 |
#ifndef INCLUDED_PLACEMENTALLOC_H_ |
| 2 |
#define INCLUDED_PLACEMENTALLOC_H_ |
| 3 |
|
| 4 |
#include <ostream> |
| 5 |
|
| 6 |
template<typename Data> |
| 7 |
class PlacementAlloc: public std::allocator<Data> |
| 8 |
{ |
| 9 |
template<typename IData> |
| 10 |
friend std::ostream &operator<<(std::ostream &out, |
| 11 |
PlacementAlloc<IData> const &alloc); |
| 12 |
Data *d_data; |
| 13 |
|
| 14 |
static char s_commonPool[]; |
| 15 |
static char *s_free; |
| 16 |
|
| 17 |
public: |
| 18 |
PlacementAlloc(); |
| 19 |
PlacementAlloc(Data const &data); |
| 20 |
PlacementAlloc(PlacementAlloc<Data> const &other); |
| 21 |
~PlacementAlloc(); |
| 22 |
operator Data &(); |
| 23 |
PlacementAlloc &operator=(Data const &data); |
| 24 |
private: |
| 25 |
char *request(); |
| 26 |
}; |
| 27 |
|
| 28 |
template<typename Data> |
| 29 |
char PlacementAlloc<Data>::s_commonPool[1000]; |
| 30 |
|
| 31 |
template<typename Data> |
| 32 |
char *PlacementAlloc<Data>::s_free = |
| 33 |
PlacementAlloc<Data>::s_commonPool; |
| 34 |
|
| 35 |
template<typename Data> |
| 36 |
PlacementAlloc<Data>::PlacementAlloc() |
| 37 |
: |
| 38 |
d_data(0) |
| 39 |
{} |
| 40 |
|
| 41 |
template<typename Data> |
| 42 |
PlacementAlloc<Data>::PlacementAlloc(Data const &data) |
| 43 |
: |
| 44 |
d_data(new(request()) Data(data)) |
| 45 |
{} |
| 46 |
|
| 47 |
template<typename Data> |
| 48 |
PlacementAlloc<Data>::PlacementAlloc(PlacementAlloc<Data> const &other) |
| 49 |
: |
| 50 |
d_data(new(request()) Data(*other.d_data)) |
| 51 |
{} |
| 52 |
|
| 53 |
template<typename Data> |
| 54 |
PlacementAlloc<Data>::~PlacementAlloc() |
| 55 |
{ |
| 56 |
d_data->~Data(); |
| 57 |
} |
| 58 |
|
| 59 |
template<typename Data> |
| 60 |
PlacementAlloc<Data>::operator Data &() |
| 61 |
{ |
| 62 |
return *d_data; |
| 63 |
} |
| 64 |
|
| 65 |
template<typename Data> |
| 66 |
PlacementAlloc<Data> &PlacementAlloc<Data>::operator=(Data const &data) |
| 67 |
{ |
| 68 |
*d_data = data; |
| 69 |
} |
| 70 |
|
| 71 |
template<typename Data> |
| 72 |
char *PlacementAlloc<Data>::request() |
| 73 |
{ |
| 74 |
char *cp = s_free; |
| 75 |
s_free += sizeof(Data); |
| 76 |
return cp; |
| 77 |
} |
| 78 |
|
| 79 |
template<typename IData> |
| 80 |
inline std::ostream &operator<<(std::ostream &out, |
| 81 |
PlacementAlloc<IData> const &alloc) |
| 82 |
{ |
| 83 |
return out << *alloc.d_data; |
| 84 |
} |
| 85 |
|
| 86 |
#endif |