#include "btMutex.h"
template <typename T>
class SmartHandlePtr{
struct Handle{
Handle(){
ptr = NULL;
cnt = 0;
}
void* ptr;
int cnt;
btLock lock;
void inc(){
btScopeLock sl(lock);
cnt++;
}
void dec(){
btScopeLock sl(lock);
cnt--;
}
};
public:
SmartHandlePtr(const T* p){
_ph = new Handle;
_ph->ptr =(void*) p;
_ph->inc();
}
~SmartHandlePtr(){
if( _ph ){
_ph->dec();
if( _ph->cnt==0){
T* p;
p = (T*)_ph->ptr;
if( p ){
delete p;
}
delete _ph;
}
}
}
SmartHandlePtr(const SmartHandlePtr& shp){
if( _ph ){
_ph->dec();
if( _ph->cnt==0){
T* p;
p = (T*)_ph->ptr;
if( p){
delete p;
}
delete _ph;
}
}
_ph = _ph;
_ph->inc();
}
bool operator==(const T* p) {
return _ph->ptr == p;
}
bool operator==(const SmartHandlePtr& shp){
return _ph == shp._ph;
}
T* operator->(){
return (T*)_ph->ptr;
}
T* get(){
if( _ph && _ph->ptr){
return (T*)_ph->ptr;
}
return NULL;
}
private:
Handle* _ph;
};