#define SGSharedPtr_HXX
#include "SGReferenced.hxx"
+#include <algorithm>
/// This class is a pointer proxy doing reference counting on the object
/// it is pointing to.
SGSharedPtr(const SGSharedPtr<U>& p) : _ptr(p.get())
{ get(_ptr); }
~SGSharedPtr(void)
- { put(); }
+ { reset(); }
SGSharedPtr& operator=(const SGSharedPtr& p)
- { assign(p.get()); return *this; }
+ { reset(p.get()); return *this; }
template<typename U>
SGSharedPtr& operator=(const SGSharedPtr<U>& p)
- { assign(p.get()); return *this; }
+ { reset(p.get()); return *this; }
template<typename U>
SGSharedPtr& operator=(U* p)
- { assign(p); return *this; }
+ { reset(p); return *this; }
T* operator->(void) const
{ return _ptr; }
{ return _ptr; }
T* release()
{ T* tmp = _ptr; _ptr = 0; T::put(tmp); return tmp; }
+ void reset()
+ { if (!T::put(_ptr)) delete _ptr; _ptr = 0; }
+ void reset(T* p)
+ { SGSharedPtr(p).swap(*this); }
bool isShared(void) const
{ return T::shared(_ptr); }
{ return _ptr != (T*)0; }
void clear()
- { put(); }
- void swap(SGSharedPtr& sharedPtr)
- { T* tmp = _ptr; _ptr = sharedPtr._ptr; sharedPtr._ptr = tmp; }
+ { reset(); }
+ void swap(SGSharedPtr& other)
+ { std::swap(_ptr, other._ptr); }
private:
- void assign(T* p)
- { get(p); put(); _ptr = p; }
void assignNonRef(T* p)
- { put(); _ptr = p; }
+ { reset(); _ptr = p; }
void get(const T* p) const
{ T::get(p); }
- void put(void)
- { if (!T::put(_ptr)) delete _ptr; _ptr = 0; }
// The reference itself.
T* _ptr;
template<typename T>
class SGWeakPtr {
public:
+ typedef T element_type;
+
SGWeakPtr(void)
{ }
SGWeakPtr(const SGWeakPtr& p) : mWeakData(p.mWeakData)
{ assign(ptr); }
template<typename U>
SGWeakPtr(const SGSharedPtr<U>& p)
- { SGSharedPtr<T> sharedPtr = p; assign(sharedPtr.get()); }
+ { assign(p.get()); }
template<typename U>
SGWeakPtr(const SGWeakPtr<U>& p)
{ SGSharedPtr<T> sharedPtr = p.lock(); assign(sharedPtr.get()); }
template<typename U>
SGWeakPtr& operator=(const SGSharedPtr<U>& p)
- { SGSharedPtr<T> sharedPtr = p; assign(sharedPtr.get()); return *this; }
+ { assign(p.get()); return *this; }
template<typename U>
SGWeakPtr& operator=(const SGWeakPtr<U>& p)
{ SGSharedPtr<T> sharedPtr = p.lock(); assign(sharedPtr.get()); return *this; }
SGWeakPtr& operator=(const SGWeakPtr& p)
{ mWeakData = p.mWeakData; return *this; }
+ template<typename U>
+ bool operator==(const SGWeakPtr<U>& rhs) const
+ { return mWeakData == rhs.mWeakData; }
+ template<typename U>
+ bool operator!=(const SGWeakPtr<U>& rhs) const
+ { return mWeakData != rhs.mWeakData; }
+ template<typename U>
+ bool operator<(const SGWeakPtr<U>& rhs) const
+ { return mWeakData < rhs.mWeakData; }
+
SGSharedPtr<T> lock(void) const
{
if (!mWeakData)
return sharedPtr;
}
+ bool expired() const
+ { return !mWeakData || mWeakData->mRefcount == 0; }
+
+ void reset()
+ { mWeakData.reset(); }
void clear()
- { mWeakData = 0; }
+ { mWeakData.reset(); }
void swap(SGWeakPtr& weakPtr)
{ mWeakData.swap(weakPtr.mWeakData); }