/
shared_ptr.cpp
108 lines (88 loc) · 2.42 KB
/
shared_ptr.cpp
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <cassert>
#include <iostream>
#include <memory>
#include <vector>
// From Wikipedia.
void shared_ptr() {
std::cout << __FUNCTION__ << std::endl;
std::shared_ptr<int> p1(new int(5));
std::shared_ptr<int> p2 = p1; // Both now own the memory.
assert(p1.use_count() == 2);
// Memory still exists, due to p2:
p1.reset();
assert(p1.get() == NULL && p2.get() != NULL);
assert(p2.use_count() == 1);
assert(p1.use_count() == 0);
// Deletes the memory, since no one else owns the memory.
p2.reset();
assert(p1.get() == NULL && p2.get() == NULL);
assert(p2.use_count() == 0);
assert(p1.use_count() == 0);
}
void shared_ptr_container() {
std::cout << __FUNCTION__ << std::endl;
std::shared_ptr<int> p1(new int(5));
std::shared_ptr<int> p2 = p1; // Both now own the memory.
assert(p1.use_count() == 2);
std::vector<std::shared_ptr<int>> v;
v.push_back(p1);
v.push_back(p1);
assert(p1.use_count() == 4);
p2.reset();
assert(p1.use_count() == 3);
assert(p2.use_count() == 0);
v.pop_back();
v.pop_back();
assert(p1.use_count() == 1);
}
void weak_ptr() {
std::cout << __FUNCTION__ << std::endl;
std::shared_ptr<int> p1(new int(5));
std::weak_ptr<int> wp1 = p1; // p1 owns the memory.
{
std::shared_ptr<int> p2 = wp1.lock(); // Now p1 and p2 own the memory.
assert(p2 != NULL);
if (p2) { // As p2 is initialized from a weak pointer,
// you have to check if the memory still exists!
// Do something with p2
}
} // p2 is destroyed. Memory is owned by p1.
assert(wp1.lock() != NULL);
assert(wp1.use_count() == 1);
p1.reset(); // Memory is deleted.
assert(wp1.lock() == NULL);
assert(wp1.use_count() == 0);
std::shared_ptr<int> p3 = wp1.lock();
// Memory is gone, so we get an empty shared_ptr.
assert(p3 == NULL);
if (p3) {
// Will not execute this.
}
}
void add_one(std::shared_ptr<int> i) {
(*i)++;
}
void make_shared() {
std::cout << __FUNCTION__ << std::endl;
std::shared_ptr<int> sp = std::shared_ptr<int>(new int(12));
assert(*sp == 12);
add_one(sp);
assert(*sp == 13);
auto sp2 = std::shared_ptr<int>(new int(12));
assert(*sp2 == 12);
add_one(sp2);
add_one(sp2);
add_one(sp2);
assert(*sp2 == 15);
auto sp3 = std::make_shared<int>(12);
assert(*sp3 == 12);
add_one(sp3);
add_one(sp3);
assert(*sp3 == 14);
}
int main() {
shared_ptr();
shared_ptr_container();
weak_ptr();
make_shared();
}