- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
class Allocator
{
public:
virtual void *Alloc (size_t) = 0;
virtual void Dealloc (void *) = 0;
struct Allocation
{
Allocator *m_pAllocator[1];
static void Dealloc (void *ptr)
{
if (ptr)
((Allocator **)ptr)[-1]->Dealloc (((Allocator **)ptr)-1);
}
};
};
class UsesAllocator
{
public:
void *operator new (size_t aSize,Allocator &aAllocator)
{
Allocator::Allocation *pResult =
(Allocator::Allocation *)
aAllocator.Alloc (aSize+sizeof (Allocator::Allocation));
if (!pResult) throw std::bad_alloc ();
pResult->m_pAllocator[0] = &aAllocator;
return pResult->m_pAllocator+1;
}
void *operator new [] (size_t aSize,Allocator &aAllocator)
{
Allocator::Allocation *pResult =
(Allocator::Allocation *)
aAllocator.Alloc (aSize+sizeof (Allocator::Allocation));
if (!pResult) throw std::bad_alloc ();
pResult->m_pAllocator[0] = &aAllocator;
return pResult->m_pAllocator+1;
}
void operator delete (void *ptr,Allocator &)
{ Allocator::Allocation::Dealloc (ptr); }
void operator delete (void *ptr)
{ Allocator::Allocation::Dealloc (ptr); }
void operator delete [] (void *ptr,Allocator &)
{ Allocator::Allocation::Dealloc (ptr); }
void operator delete [] (void *ptr)
{ Allocator::Allocation::Dealloc (ptr); }
};
...
class MyClass: /*virtual*/ public UsesAllocator
{
public:
...
};
...
MyClass *PROFIT = new (allocatorOfOurInterest) MyClass (...);