-
Notifications
You must be signed in to change notification settings - Fork 80
/
8.8shared_ptr的共享对象.cpp
47 lines (42 loc) · 1.05 KB
/
8.8shared_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
#include"print.h"
#include<memory>
struct Thing {
std::string thname{ "unk" };
Thing() { print("default ctor:{}\n", thname); }
Thing(std::string n) :thname(n) { print("param ctor:{}\n", thname); }
~Thing() { print("dtor :{}\n", thname); }
};
void check_thing_ptr(const std::shared_ptr<Thing>& p) {
if (p)print("{} use count: {}\n", p->thname, p.use_count());
else print("invalid pointer\n");
}
int main() {
std::shared_ptr<Thing>p1{ new Thing("Thing 1") };
auto p2 = std::make_shared<Thing>("Thing 2");
check_thing_ptr(p1);
check_thing_ptr(p2);
{
auto pa = p1;
auto pb = p1;
auto pc = p1;
auto pd = p1;
check_thing_ptr(p1);
check_thing_ptr(pa);
check_thing_ptr(pb);
check_thing_ptr(pc);
check_thing_ptr(pd);
}
check_thing_ptr(p1);
auto p3 = p1;
check_thing_ptr(p1);
p3.reset();
check_thing_ptr(p1);
p1.reset(new Thing{ "🥵" }, [](Thing* p) {
puts("自定义删除器被调用");
delete p;
});
std::shared_ptr<Thing>p4{ new Thing("Thing 4"),[](Thing* p) {
puts("自定义删除器被调用!!!🤡🤡");
delete p;
} };
}