-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMove_semantics.cpp
More file actions
75 lines (63 loc) · 1.83 KB
/
Copy pathMove_semantics.cpp
File metadata and controls
75 lines (63 loc) · 1.83 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
#include <iostream>
#include <memory>
#include <utility> // move, pair, swap, exchange, *forward -> handle vari rvalue & lvalue
/*
std::pair<int, double> get_market_data() {
return {1024, 99.85};
}
int main() {
// C++17
auto [id, price] = get_market_data();
*/
/*
struct Node {
int* data;
Node(Node&& other) noexcept
// other.data = data, other.data = nullptr
: data(std::exchange(other.data, nullptr)) {}
};
*/
// Class template(Move semantics)
template <typename T>
class resourcemanager{
private:
std::unique_ptr<T> ptr;
public:
explicit resourcemanager(std::unique_ptr<T> resource)
:ptr(std::move(resource)){
std::cout << "Resource";
}
~resourcemanager() = default;
// Move struct/assignment func
resourcemanager(resourcemanager && other ) noexcept = default; // rvalues
resourcemanager& operator=(resourcemanager && other) noexcept = default;
// Copy struct/assignment func
resourcemanager(resourcemanager & other) noexcept = delete; // lvalues
resourcemanager& operator=(resourcemanager & other) noexcept = delete;
// business api
void process(){
if(ptr){
std::cout << "";
execute();
}
}
void execute(){
if(ptr){
ptr -> process(); // Use child class's api (if exists)
}
}
// Provide visit api
T* get() const {return ptr.get();}
};
struct algorithm{
void process(){
std::cout << "Hello" << std::endl;
}
~algorithm() = default;
};
int main(){
std::unique_ptr<algorithm> myal;
// Transfer to resource class's ptr
resourcemanager<algorithm> manager(std::move(myal));
manager.process();
}