したがって、私のカスタム アロケーターの実装には、2 つの静的変数を持つ基本クラスがあり、1 つはアロケーターのインスタンスを追跡し、もう 1 つはメモリ プールです。
template <typename T>
class Allocator : public Base_Allocator
{
public:
// Required types
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
template <typename U>
struct rebind
{
typedef Allocator<U> other;
};
// Required Opeartions
explicit Allocator(void) : Base_Allocator()
{
}
~Allocator(void) { }
Allocator(const Allocator& a) : Base_Allocator()
{
} // copy constructor
pointer address(reference value) const { return &value; }
const_pointer address(const_reference value) const { return &value; }
size_type max_size(void) const { size_type m = 4096; return m; }
pointer allocate(size_type n)
{
return static_cast<value_type*>( Base_Allocator::m_pMemMngr->Alloc( sizeof(value_type) * n) );
}
void deallocate(pointer p, size_type n) {
Base_Allocator::m_pMemMngr->Free(p);
}
void construct(pointer p, const T& value) {
new((T*)p) T(value);
}
void destroy(pointer p) {
p->~T();
}
bool operator == (const Allocator& right) const { return true; }
bool operator != (const Allocator& right) const { return false; }
};
そして、ここに基本クラスがあります...
class Base_Allocator
{
public:
static int m_icount;
static MemoryManager* m_pMemMngr;
public:
Base_Allocator(void)
{
m_icount++;
if(!m_pMemMngr)
{
NEW(m_pMemMngr);
m_pMemMngr->Init();
}
}
~Base_Allocator(void)
{
m_icount--;
if(m_icount<0)
{
SAFE_DELETE(m_pMemMngr);
}
}
};
これが静的メンバーの定義です
#include "Base.h"
int Base_Allocator::m_icount = 0;
MemoryManager* Base_Allocator::m_pMemMngr = nullptr;
ここでの私のことは、メモリが決して解放されないということです。私はそれを forward_list に渡しています。この forward リストは 3 つのアロケーターを作成しますが、3 つも削除します。これが、基本クラスが 0 未満になったときにのみメモリを解放する理由です。しかし、物事はあまりうまくいきませんでした. -1 に到達することはないので、メモリプール内のメモリを解放することはありません。どんなアイデアでも大歓迎です。