-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_safe.hpp
More file actions
43 lines (37 loc) · 855 Bytes
/
memory_safe.hpp
File metadata and controls
43 lines (37 loc) · 855 Bytes
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
#pragma once
template <typename T>
class MemorySafe {
T value1;
T value2;
// Swap value1 and value2 based on this flag
bool flag = true;
public:
MemorySafe(T value): value1(value) {}
// value getter
const T& unwrap() const {
if (flag) {
return value1;
} else {
return value2;
}
};
void update(const T& value) {
if (flag) {
value2 = value;
// maybe set a random value here
} else {
value1 = value;
}
flag = !flag;
}
// implement for std::cout
friend std::ostream& operator<<(std::ostream& os, const MemorySafe& ms) {
os << ms.unwrap();
return os;
}
// implement =
MemorySafe& operator=(const T& value) {
update(value);
return *this;
}
};