// --------------------------------------------- SmartPointerTable.h
#ifndef SMARTPOINTERTABLE_H
#define SMARTPOINTERTABLE_H
#include <map>
#include <iostream>
typedef std::map<void*, unsigned> rctable_t;
class SmartPointerTable
{
private:
static bool entryExists(void* p)
{
rctable_t::iterator found = SmartPointerTable::s_RefCntTable.find(p);
return found != s_RefCntTable.end();
}
protected:
static rctable_t s_RefCntTable;
static void increment(void* p)
{
if(entryExists(p)) {
s_RefCntTable[p]++;
} else {
s_RefCntTable[p] = 1;
}
}
static void decrement(void* p)
{
if(entryExists(p)) {
s_RefCntTable[p]--;
if(s_RefCntTable[p] == 0)
{
s_RefCntTable.erase(p);
}
}
}
static unsigned getCount(void* p)
{
if(entryExists(p)) {
return s_RefCntTable[p];
}
return 0;
}
SmartPointerTable(){}
virtual ~SmartPointerTable() = 0;
};
rctable_t SmartPointerTable::s_RefCntTable;
SmartPointerTable::~SmartPointerTable()
{
}
#endif
// --------------------------------------------- SmartPointer.h
#ifndef SMARTPOINTER_H
#define SMARTPOINTER_H
#include "SmartPointerTable.h"
template < typename T >
class SmartPointer : private SmartPointerTable
{
private:
T m_Ptr;
public:
SmartPointer(T tp)
{
m_Ptr = tp;
if(m_Ptr != 0)
{
SmartPointerTable::increment(m_Ptr);
}
}
~SmartPointer()
{
if(m_Ptr != 0)
{
SmartPointerTable::decrement(m_Ptr);
if(SmartPointerTable::getCount(m_Ptr) == 0)
{
delete m_Ptr;
}
}
}
T get()
{
return m_Ptr;
}
};
#endif