-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathself_managed_int.cpp
69 lines (59 loc) · 1.9 KB
/
self_managed_int.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
/*****************************************************************//**
* \file self_managed_int.cpp
* \brief Use case of enable_shared_from_this to obtain this pointer
* in the form of a std::shared_ptr<typename T>.
*
* \author Xuhua Huang
* \date December 03, 2022
*********************************************************************/
#include <iomanip>
#include <iostream>
#include <memory>
class self_managed_int : public std::enable_shared_from_this<self_managed_int> {
public:
/**
* Default and overloaded constructor
* Copy constructor and virtual destructor.
*/
self_managed_int() = default;
self_managed_int(const int value)
: m_value(value) {}
self_managed_int(const self_managed_int& rhs) { value() = rhs.value(); }
virtual ~self_managed_int() = default;
/**
* Overloaded int() and spaceship comparison operator.
*/
operator int() { return m_value; }
inline int operator<=>(const self_managed_int& rhs) { return (value() <=> rhs.value())._Value; }
/* Mutator and accessor */
[[nodiscard]]
inline int value() const {
return m_value;
}
[[nodiscard]]
inline int& value() {
return m_value;
}
void print() const {
std::cout << std::quoted("self_managed_int::print()") << " -> this->value() = " << m_value << "\n";
}
[[nodiscard]]
std::shared_ptr<self_managed_int> get_shared() {
return shared_from_this();
}
private:
int m_value;
};
int main(void) {
// test utility print function
std::shared_ptr<self_managed_int> shared_int = std::make_shared<self_managed_int>(12);
shared_int->print();
// test shared_from_this()
auto p_shared_int = shared_int->get_shared();
// equivalent to the following:
// p = shared_int->shared_from_this();
p_shared_int->value() = 24;
p_shared_int->print();
system("pause");
return EXIT_SUCCESS;
}