-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp14_unique_ptr.cpp
More file actions
81 lines (61 loc) · 1.58 KB
/
cpp14_unique_ptr.cpp
File metadata and controls
81 lines (61 loc) · 1.58 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
74
75
76
77
78
79
80
81
#include <iostream>
#include <memory>
class X {
public:
X() {
instance_count++;
instance_id = instance_count;
printf("[ %2d ] X's Constructor\n", instance_id);
}
~X() {
printf("[ %2d ] X's Destructor\n", instance_id);
}
void SayHi() {
printf("[ %2d ] Hi from X\n", instance_id);
}
private:
static int instance_count;
int instance_id;
};
int X::instance_count = 0;
void print_line() {
std::cout << "----------------------------------------------------------\n"; return;
}
void test_with_raw_ptr() {
print_line();
X *x = new X{};
x->SayHi();
print_line();
return;
}
// Example on how to return a unique_ptr;
// Here, Move semantics come into play.
// Ref: https://stackoverflow.com/questions/9827183/why-am-i-allowed-to-copy-unique-ptr
auto getXsUniquePtr() {
auto x = std::make_unique<X>();
// The following line is equivalent to return std::move(x)
return x;
}
void test_with_uniq_ptr() {
print_line();
auto x = std::make_unique<X>();
x->SayHi();
print_line();
// Unique Ptr cannot be copied.
// auto y = x;
// Reason:
// unique_ptr(const unique_ptr&) = delete;
// unique_ptr& operator=(const unique_ptr&) = delete;
// Example on how to return a unique_ptr;
// Here, Move semantics come into play.
// Ref: https://stackoverflow.com/questions/9827183/why-am-i-allowed-to-copy-unique-ptr
auto z = getXsUniquePtr();
x->SayHi();
print_line();
return;
}
int main() {
test_with_raw_ptr();
test_with_uniq_ptr();
return 0;
}