mirror of
https://github.com/RetroShare/RetroShare.git
synced 2024-10-01 02:35:48 -04:00
4cab2aaa65
(automates comparisons) fixed some unit tests caused by copy constructor removal git-svn-id: http://svn.code.sf.net/p/retroshare/code/trunk@7302 b45a01b8-16f6-495d-af2f-9b41ad6348cc
107 lines
1.6 KiB
C++
107 lines
1.6 KiB
C++
/*
|
|
* rssharedptr.h
|
|
*
|
|
* Created on: 16 Apr 2014
|
|
* Author: crispy
|
|
*/
|
|
|
|
#ifndef RSSHAREDPTR_H_
|
|
#define RSSHAREDPTR_H_
|
|
|
|
#include <stdlib.h>
|
|
|
|
/*!
|
|
* Not thread safe!!
|
|
*/
|
|
template<class T>
|
|
class RsSharedPtr
|
|
{
|
|
public:
|
|
|
|
RsSharedPtr() : mShared(NULL), mCount(NULL) {}
|
|
|
|
RsSharedPtr(T* shared)
|
|
: mShared(shared), mCount(new int(0)), mSharedPtrMutex(new RsMutex("SharedMutex"))
|
|
{
|
|
mCount++;
|
|
}
|
|
|
|
RsSharedPtr(const RsSharedPtr<T>& rsp)
|
|
{
|
|
rsp.lock();
|
|
mShared = rsp.mShared;
|
|
mCount = rsp.mCount;
|
|
mCount++;
|
|
mSharedPtrMutex = rsp.mSharedPtrMutex;
|
|
rsp.unlock();
|
|
|
|
}
|
|
|
|
void operator=(const RsSharedPtr<T>& rsp)
|
|
{
|
|
rsp.lock();
|
|
mSharedPtrMutex = rsp.mSharedPtrMutex;
|
|
DecrementAndDeleteIfLast();
|
|
mShared = rsp.mShared;
|
|
RepointAndIncrement(rsp.mCount);
|
|
|
|
mSharedPtrMutex->unlock();
|
|
}
|
|
|
|
T* release() {
|
|
|
|
lock();
|
|
|
|
mCount--; T* temp = mShared; mShared = NULL;
|
|
|
|
unlock();
|
|
|
|
return temp;
|
|
}
|
|
T* get() { return mShared; }
|
|
|
|
T& operator*(){ return *mShared; }
|
|
T* operator->(){ return mShared; }
|
|
|
|
~RsSharedPtr()
|
|
{
|
|
DecrementAndDeleteIfLast();
|
|
}
|
|
private:
|
|
|
|
void DecrementAndDeleteIfLast()
|
|
{
|
|
mCount--;
|
|
if(mCount == 0 && mShared != NULL)
|
|
{
|
|
delete mShared;
|
|
delete mCount;
|
|
}
|
|
|
|
mShared = NULL;
|
|
mCount = NULL;
|
|
}
|
|
|
|
void RepointAndIncrement(int* count)
|
|
{
|
|
mCount = count;
|
|
mCount++;
|
|
|
|
}
|
|
|
|
void lock() const { mSharedPtrMutex->lock(); }
|
|
void unlock() const { mSharedPtrMutex->unlock(); }
|
|
|
|
private:
|
|
|
|
int* mCount;
|
|
T* mShared;
|
|
RsMutex* mSharedPtrMutex;
|
|
|
|
};
|
|
|
|
template<class T>
|
|
RsSharedPtr<T> rs_make_shared(T* ptr){ return RsSharedPtr<T>(ptr); }
|
|
|
|
#endif /* RSSHAREDPTR_H_ */
|