-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRefCount.h
More file actions
81 lines (63 loc) · 1.65 KB
/
Copy pathRefCount.h
File metadata and controls
81 lines (63 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#ifndef REF_COUNT_H_
#define REF_COUNT_H_
#include <atomic>
#include <cstddef>
class RefCount
{
public:
RefCount() : mRefCount( 0 ) {}
void AddRef() const
{
mRefCount.fetch_add( 1, std::memory_order_relaxed );
}
void Release() const
{
if ( mRefCount.fetch_sub( 1, std::memory_order_acq_rel ) == 1 )
{
onRefCountZero();
}
}
int getRefCountForDebug() const { return mRefCount.load( std::memory_order_relaxed ); }
protected:
virtual void onRefCountZero() const { delete this; }
virtual ~RefCount() {}
private:
mutable std::atomic<int> mRefCount;
};
template<class T>
class SmartPtr
{
public:
SmartPtr() : mObj( nullptr ) {}
SmartPtr( T *obj ) : mObj( obj ) { if ( mObj != nullptr ) mObj->AddRef(); }
SmartPtr( const SmartPtr &ptr ) : mObj( ptr.mObj ) { if ( mObj != nullptr ) mObj->AddRef(); }
~SmartPtr() { if ( mObj != nullptr ) mObj->Release(); }
SmartPtr &operator=( const SmartPtr &ptr )
{
*this = ptr.mObj;
return *this;
}
SmartPtr &operator=( T *obj )
{
if ( obj != nullptr )
{
obj->AddRef();
}
if ( mObj != nullptr )
mObj->Release();
mObj = obj;
return *this;
}
bool operator==( const T *obj ) const { return ( mObj == obj ); }
bool operator==( const SmartPtr &ptr ) const { return ( mObj == ptr.mObj ); }
bool operator!=( const T *obj ) const { return ( mObj != obj ); }
bool operator!=( const SmartPtr &ptr ) const { return ( mObj != ptr.mObj ); }
T* operator->() { return mObj; }
const T* operator->() const { return mObj; }
operator T*() { return mObj; }
operator const T*() const { return mObj; }
const T* getObjectForDebug() const { return mObj; }
private:
T *mObj;
};
#endif // REF_COUNT_H_