-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared_ptr_ref_cnt.cpp
More file actions
74 lines (53 loc) · 1.34 KB
/
shared_ptr_ref_cnt.cpp
File metadata and controls
74 lines (53 loc) · 1.34 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
#include <iostream>
#include <thread>
#include <unistd.h>
#include <string>
#include <sstream>
#include <map>
using namespace std;
class VarStore {
public:
VarStore(int value) : var_(value) {}
void SetVar(int value) { var_ = value; }
int GetVar() { return var_; }
private:
int var_{0};
};
map<int, shared_ptr<VarStore>> map_;
using Map = map<int, shared_ptr<VarStore>>;
void StoreValIntoMap(int index, shared_ptr<VarStore> ptr) {
map_[index] = ptr;
}
void StoreRefIntoMap(int index, shared_ptr<VarStore>& ptr) {
map_[index] = ptr;
}
shared_ptr<VarStore> GetValByIndex(int key) {
return map_[key];
}
shared_ptr<VarStore>& GetValByRef(int key) {
return map_[key];
}
void FnByVal(shared_ptr<VarStore> ptr) {
cout << __func__ << ptr.use_count() << endl;
}
void FnByRef(shared_ptr<VarStore>& ptr) {
ptr->SetVar(10);
cout << __func__ << ptr.use_count() << endl;
}
int main() {
shared_ptr<VarStore> sptr = make_shared<VarStore>(1);
StoreValIntoMap(1, std::move(sptr));
//StoreRefIntoMap(1, sptr);
cout << sptr.use_count() << endl;
auto &objx = GetValByRef(1);
cout << objx.use_count() << endl;
FnByVal(objx);
cout << objx.use_count() << endl;
FnByRef(objx);
cout << __func__ << objx->GetVar() << endl;
cout << objx.use_count() << endl;
return 0;
auto obj = GetValByIndex(1);
cout << obj.use_count() << endl;
return 0;
}