-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathsmart-pointer.cpp
100 lines (82 loc) · 2.71 KB
/
smart-pointer.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
#include <memory> // smart pointer
#include <iostream>
#include <array>
class MyClass {
public:
MyClass(); // default ctor
~MyClass(); // dtor
};
MyClass::MyClass() {
std::cout << "[default ctor] MyClass()" << std::endl;
}
MyClass::~MyClass() {
std::cout << "[dtor ] ~MyClass()" << std::endl;
}
MyClass func1() { // allocate on Stack, will be RVO to caller stack
auto foo = MyClass();
std::cout << &foo << std::endl;
return foo;
}
MyClass* func2() { // need explicit delete, or it will have memory leak
auto foo = new MyClass();
std::cout << foo << std::endl;
return foo;
}
auto func3() { // unique_ptr, delete object automatically when there is no owner
auto foo = std::make_unique<MyClass>(); // make_unique is C++14
std::cout << foo.get() << std::endl;
return foo;
}
auto func4() { // shared_ptr, delete object automatically when there is no sharer
auto foo = std::make_shared<MyClass>(); // make_shared is C++11
std::cout << foo.get() << std::endl;
return foo;
}
template<typename T>
void share_with_you(std::shared_ptr<T> ptr) {
std::cout << "Share Count: " << ptr.use_count() << std::endl;
}
int main() {
std::cout << "=== Allocate on Stack ===" << std::endl;
{
auto foo = func1();
std::cout << &foo << std::endl;
}
std::cout << "=== Allocate on Heap (without explicit delete) ===" << std::endl;
{
auto foo = func2();
std::cout << foo << std::endl;
}
std::cout << "=== Allocate on Heap (unique_ptr) ===" << std::endl;
{
auto foo = func3();
std::cout << foo.get() << std::endl;
}
std::cout << "=== Allocate on Heap (shared_ptr) ===" << std::endl;
{
auto foo = func4();
std::cout << foo.get() << std::endl;
std::cout << "Share Count: " << foo.use_count() << std::endl;
share_with_you(foo);
std::cout << "Share Count: " << foo.use_count() << std::endl;
}
std::cout << "=== Allocate on Heap (return shared_ptr, assign weak_ptr) ===" << std::endl;
{
std::weak_ptr<MyClass> foo = func4(); // this will not keep the object
std::cout << foo.use_count() << std::endl;
auto ptr = foo.lock();
if (ptr == nullptr) { // or foo.expired()
std::cout << "I don't have object :(" << std::endl;
}
}
std::cout << "=== shared_ptr and array ===" << std::endl;
{
std::shared_ptr<MyClass> foo(new MyClass[3],
[](MyClass* ptr){ delete [] ptr; });
}
std::cout << "=== shared_ptr and array ===" << std::endl;
{
auto foo = std::make_shared<std::array<MyClass, 3>>();
}
return 0;
}