forked from anastasiak2512/basicDemo
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlifetime_safety_samples.cpp
106 lines (88 loc) · 1.94 KB
/
lifetime_safety_samples.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
#pragma clang diagnostic push
#pragma ide diagnostic ignored "modernize-use-trailing-return-type"
#pragma ide diagnostic ignored "cppcoreguidelines-avoid-c-arrays"
#include <iostream>
#include <vector>
#include <optional>
//The simplest sample for Lifetimes proposal, how to track the pointer through the code.
void sample1() {
int* p = nullptr;
{
int x = 0;
p = &x;
*p = 42;
}
*p = 42;
}
void sample2() {
int *p = nullptr;
{
int x = 0;
p = &x;
std::cout << *p;
}
std::cout << *p;
}
//All rules apply equally to any generalized “Pointer” type that refers indirectly to another object it doesn’t own.
void sample3() {
std::string_view s;
{
char a[100];
s = a;
std::cout << s[0];
}
std::cout << s[0];
}
std::vector<int>::iterator sample4() {
std::vector<int> v;
auto p = v.begin();
return p;
}
const char* sample5() {
auto str = std::string("text");
const char *ps = str.c_str();
return ps;
}
void sample6() {
const char *ptr;
{
auto str = std::string("text");
ptr = str.c_str();
char x = *ptr;
}
char y = *ptr;
}
int &sample7() {
std::optional<int> o;
int &i = *o;
return i;
}
const char *sample_string_view() {
auto string = std::string("text");
auto view = std::string_view(string);
auto ptr = view.begin();
return ptr;
}
//Sample 9
struct [[gsl::Owner(int)]] MyIntOwner {
MyIntOwner();
int &operator*();
};
struct [[gsl::Pointer(int)]] MyIntPointer {
MyIntPointer(int *p = nullptr);
MyIntPointer(const MyIntOwner &);
int &operator*();
MyIntOwner toOwner();
};
MyIntPointer sample9() {
const MyIntOwner owner = MyIntOwner();
auto pointer = MyIntPointer(owner);
return pointer;
}
std::string get_string();
void sample10()
{
std::string_view sv = get_string();
auto c = sv.at(0);
}
#pragma clang diagnostic pop