-
Notifications
You must be signed in to change notification settings - Fork 1
/
smart_pointers.cpp
49 lines (45 loc) · 1.13 KB
/
smart_pointers.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
#include <iostream>
#include <memory>
class Test {
private:
int x;
public:
Test(int i): x(i) { std::cout << "constructor" << std::endl; }
void show() const { std::cout << "show: " << x << std::endl; }
~Test() { std::cout << "destructor" << std::endl; }
};
int main() {
if (false) {
// Test *p = new Test(3);
std::unique_ptr<Test> p(new Test(3));
// std::unique_ptr<Test> p = std::make_unique<Test>(3);
p->show();
}
auto wp_stat = [](const std::weak_ptr<Test> &p) {
std::cout << (p.expired()? "expired": "live") << ": " << p.use_count() << std::endl;
if (!p.expired()) p.lock()->show();
};
std::weak_ptr<Test> wp, wq;
{
// Test *p = nullptr;
// std::shared_ptr<Test> p(nullptr);
std::shared_ptr<Test> p = std::make_shared<Test>(3);
wp = p;
wp_stat(wp); wp_stat(wq);
{
// Test *q = new Test(4);
// std::shared_ptr<Test> q(new Test(4));
std::shared_ptr<Test> q = std::make_shared<Test>(4);
p = q;
std::cout << q.use_count() << std::endl;
wp_stat(wp); wp_stat(wq);
wq = p;
wp_stat(wp); wp_stat(wq);
}
wp = wq;
p->show();
wp_stat(wp); wp_stat(wq);
}
wp_stat(wp); wp_stat(wq);
return 0;
}