-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared_ptr_tencent.cpp
More file actions
59 lines (55 loc) · 1.49 KB
/
shared_ptr_tencent.cpp
File metadata and controls
59 lines (55 loc) · 1.49 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
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
// https://cloud.tencent.com/developer/article/1688444
template <class T>
class Shared_Ptr {
public:
Shared_Ptr(T *ptr = nullptr)
: _pPtr(ptr), _pRefCount(new int(1)), _pMutex(new mutex) {}
~Shared_Ptr() { Release(); }
Shared_Ptr(const Shared_Ptr<T> &sp)
: _pPtr(sp._pPtr), _pRefCount(sp._pRefCount), _pMutex(sp._pMutex) {
AddRefCount();
}
Shared_Ptr<T> &operator=(const Shared_Ptr<T> &sp) {
// if (this != &sp)
if (_pPtr != sp._pPtr) {
// 释放管理的旧资源
Release();
// 共享管理新对象的资源,并增加引用计数
_pPtr = sp._pPtr;
_pRefCount = sp._pRefCount;
_pMutex = sp._pMutex;
AddRefCount();
}
return *this;
}
T &operator*() { return *_pPtr; }
T *operator->() { return _pPtr; }
int UseCount() { return *_pRefCount; }
T *Get() { return _pPtr; }
void AddRefCount() {
_pMutex->lock();
++(*_pRefCount);
_pMutex->unlock();
}
private:
void Release() {
bool deleteflag = false;
_pMutex->lock();
if (--(*_pRefCount) == 0) {
delete _pRefCount;
delete _pPtr;
deleteflag = true;
}
_pMutex->unlock();
if (deleteflag == true)
delete _pMutex;
}
private:
int *_pRefCount;
T *_pPtr;
mutex *_pMutex;
};