46 lines
1,015 B
C++
46 lines
1,015 B
C++
#ifndef SHAREDPTR_H_
|
|
#define SHAREDPTR_H_
|
|
|
|
template <class T>
|
|
class SharedPtr {
|
|
private:
|
|
class Counter {
|
|
public:
|
|
Counter(T *o) : object(o), refCount(1) {}
|
|
~Counter() {delete object;}
|
|
|
|
T *object;
|
|
unsigned int refCount;
|
|
};
|
|
|
|
Counter *counter;
|
|
|
|
public:
|
|
SharedPtr(T *o) : counter(new Counter(o)) {}
|
|
|
|
SharedPtr(const SharedPtr<T> &c) : counter(c.counter) {
|
|
counter->refCount++;
|
|
}
|
|
|
|
virtual ~SharedPtr() {
|
|
if(--counter->refCount == 0)
|
|
delete counter;
|
|
}
|
|
|
|
SharedPtr<T>& operator=(const SharedPtr<T>& c) {
|
|
c.counter->refCount++;
|
|
if(--counter->refCount == 0)
|
|
delete counter;
|
|
|
|
counter = c.counter;
|
|
return *this;
|
|
}
|
|
|
|
T* operator->() {return counter->object;}
|
|
T& operator*() {return *counter->object;}
|
|
|
|
const T* operator->() const {return counter->object;}
|
|
const T& operator*() const {return *counter->object;}
|
|
};
|
|
|
|
#endif /*SHAREDPTR_H_*/
|