Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tunatoksoz/347108 to your computer and use it in GitHub Desktop.
Save tunatoksoz/347108 to your computer and use it in GitHub Desktop.
/*
* Reference.h
*
* Created on: Mar 28, 2010
* Author: tehlike
*/
#include "../Threading/Mutex.h"
#ifndef REFERENCE_H_
#define REFERENCE_H_
template <typename T>
class Reference
{
private:
T* item;
int* activeInstancesCounter;
Mutex* mutex;
bool DecrementUsage()
{
bool shouldDelete;
mutex->Lock();
(*activeInstancesCounter)--;
shouldDelete=(*activeInstancesCounter);
mutex->Unlock();
return shouldDelete;
}
void IncrementUsage()
{
mutex->Lock();
(*activeInstancesCounter)++;
mutex->Unlock();
}
public:
Reference(const T* item)
{
this->item=item;
this->activeInstancesCounter=new int;
this->mutex=new Mutex();
}
Reference(const Reference r)
{
this->item=r.item;
this->activeInstancesCounter=r.activeInstancesCounter;
this->mutex=r.mutex;
IncrementUsage();
}
T& operator()()
{
return *T;
}
virtual ~Reference()
{
if(DecrementUsage())
{
delete item;
delete mutex;
}
}
};
#endif /* REFERENCE_H_ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment