2012-09-08 02:50:37 +00:00
|
|
|
#ifndef _FC_SHARED_PTR_HPP_
|
|
|
|
|
#define _FC_SHARED_PTR_HPP_
|
|
|
|
|
#include <fc/utility.hpp>
|
|
|
|
|
|
|
|
|
|
namespace fc {
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @brief used to create reference counted types.
|
|
|
|
|
*
|
|
|
|
|
* Must be a virtual base class that is initialized with the
|
|
|
|
|
*
|
|
|
|
|
*/
|
|
|
|
|
class retainable {
|
|
|
|
|
public:
|
|
|
|
|
retainable();
|
|
|
|
|
void retain();
|
|
|
|
|
void release();
|
|
|
|
|
int32_t retain_count()const;
|
|
|
|
|
|
|
|
|
|
protected:
|
2012-09-09 23:44:49 +00:00
|
|
|
virtual ~retainable();
|
2012-09-08 02:50:37 +00:00
|
|
|
private:
|
|
|
|
|
volatile int32_t _ref_count;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
|
class shared_ptr {
|
|
|
|
|
public:
|
|
|
|
|
shared_ptr( T* t, bool inc = false )
|
2012-09-09 23:44:49 +00:00
|
|
|
:_ptr(t) { if( inc ) t->retain(); }
|
|
|
|
|
|
|
|
|
|
shared_ptr():_ptr(nullptr){}
|
2012-09-08 02:50:37 +00:00
|
|
|
|
|
|
|
|
shared_ptr( const shared_ptr& p ) {
|
|
|
|
|
_ptr = p._ptr;
|
|
|
|
|
if( _ptr ) _ptr->retain();
|
|
|
|
|
}
|
|
|
|
|
shared_ptr( shared_ptr&& p ) {
|
|
|
|
|
_ptr = p._ptr;
|
2012-09-09 23:44:49 +00:00
|
|
|
p._ptr = nullptr;
|
2012-09-08 02:50:37 +00:00
|
|
|
}
|
2012-09-09 23:44:49 +00:00
|
|
|
~shared_ptr() { if( _ptr ) { _ptr->release(); } }
|
|
|
|
|
|
2012-09-14 04:05:08 +00:00
|
|
|
shared_ptr& reset( T* v = 0, bool inc = false ) {
|
2012-09-09 03:46:19 +00:00
|
|
|
if( v == _ptr ) return *this;
|
2012-09-08 02:50:37 +00:00
|
|
|
if( _ptr ) _ptr->release();
|
|
|
|
|
_ptr = v;
|
2012-09-14 04:05:08 +00:00
|
|
|
if( _ptr && inc ) _ptr->retain();
|
2012-09-09 03:46:19 +00:00
|
|
|
return *this;
|
2012-09-08 02:50:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
shared_ptr& operator=(const shared_ptr& p ) {
|
|
|
|
|
shared_ptr tmp(p);
|
2012-09-09 15:12:15 +00:00
|
|
|
fc::swap(tmp._ptr,_ptr);
|
2012-09-08 02:50:37 +00:00
|
|
|
return *this;
|
|
|
|
|
}
|
|
|
|
|
shared_ptr& operator=(shared_ptr&& p ) {
|
2012-09-09 15:12:15 +00:00
|
|
|
fc::swap(_ptr,p._ptr);
|
2012-09-08 02:50:37 +00:00
|
|
|
return *this;
|
|
|
|
|
}
|
|
|
|
|
T& operator* ()const { return *_ptr; }
|
|
|
|
|
T* operator-> ()const { return _ptr; }
|
|
|
|
|
|
|
|
|
|
bool operator==( const shared_ptr& p )const { return get() == p.get(); }
|
|
|
|
|
bool operator<( const shared_ptr& p )const { return get() < p.get(); }
|
|
|
|
|
T * get() const { return _ptr; }
|
|
|
|
|
|
|
|
|
|
bool operator!()const { return _ptr == 0; }
|
|
|
|
|
operator bool()const { return _ptr != 0; }
|
|
|
|
|
private:
|
|
|
|
|
T* _ptr;
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#endif
|