SafePtr.cpp.
(B)Leading Edge
Simple Memory Management Classes
Jack Reeves
Listing 3. SafePtr.cpp.
#include "SafePtr.h"
namespace BEST {
//
// SafePtrBase
//
SafePtrBase::PtrMap SafePtrBase::_thePtrMap;
SafePtrBase::PtrMap::iterator SafePtrBase::_nullPtr;
bool SafePtrBase::_initialized = init();
// static functions
bool
SafePtrBase::init()
{
// null pointer entry - can't be removed
_nullPtr = _thePtrMap.insert(
PtrMap::value_type(null, Data())
).first;
(*_nullPtr).second.cnt = 1;
return true;
}
// construct
SafePtrBase::SafePtrBase(void* p)
: _ip(_nullPtr)
{
if (p) {
_ip = _thePtrMap.insert(
PtrMap::value_type(p, Data())
).first;
(*_ip).second.owned = true;
}
ref();
}
// Utility functions
void*
SafePtrBase::remove() const
{
void* = (*_ip).first;
bool owned = (*_ip).second.owned;
_thePtrMap.erase(_ip);
if (owned) return p;
return null;
}
void
SafePtrBase::error() const
{
throw std::domain_error(
"Exception: std::domain_error(null reference)"
);
}
} //> namespace