1 2 3 4 5 6 7 8 9 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
#ifndef __shared_ptr__
#define __shared_ptr__
#include "base_cpp/exception.h"
#include "base_cpp/red_black.h"
#include "base_cpp/os_sync_wrapper.h"
namespace indigo
{
class SharedPtrStaticData
{
protected:
static RedBlackMap<void *, int> _counters;
static OsLock _lock;
};
DECL_EXCEPTION(SharedPtrError);
template <typename T> class SharedPtr : public SharedPtrStaticData
{
public:
explicit SharedPtr (T *ptr = 0)
{
_ptr = ptr;
_capture();
}
~SharedPtr ()
{
_release();
}
T * get () const
{
return _ptr;
}
T & ref () const
{
if (_ptr == 0)
throw Error("no reference");
return *_ptr;
}
T * operator -> () const
{
if (_ptr == 0)
throw Error("no reference");
return _ptr;
}
void reset (T *ptr)
{
if (ptr != _ptr)
{
_release();
_ptr = ptr;
_capture();
}
}
DECL_TPL_ERROR(SharedPtrError);
protected:
void _release ()
{
OsLocker locker(_lock);
if (_ptr == 0)
return;
int &counter = _counters.at(_ptr);
counter--;
if (counter == 0)
{
_counters.remove(_ptr);
delete _ptr;
}
}
void _capture ()
{
OsLocker locker(_lock);
if (_ptr == 0)
return;
int *counter = _counters.at2(_ptr);
if (counter == 0)
_counters.insert(_ptr, 1);
else
(*counter)++;
}
T *_ptr;
private:
SharedPtr (const SharedPtr &); // no implicit copy
};
}
#endif
|