-
Notifications
You must be signed in to change notification settings - Fork 0
/
200922_move_forward.cpp
79 lines (69 loc) · 1.35 KB
/
200922_move_forward.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
#include <type_traits>
#include <string>
#include <cstdio>
template <typename T>
typename std::remove_reference<T>::type&&
move(T&& param)
{
typedef typename std::remove_reference<T>::type&& ReturnType;
return static_cast<ReturnType>(param);
}
template <typename T>
T&&
forward(typename std::remove_reference<T>::type& param)
{
return static_cast<T&&>(param);
}
class A
{
public:
A() {}
A(const A& rhs) { puts("A(const A&)"); }
A(A&& rhs) { puts("A(A&&)"); }
A& operator=(const A& rhs) { puts("A& operator=(const A&)"); return *this; }
A& operator=(A&& rhs) { puts("A& operator=(A&&)"); return *this; }
void swapCopy(A& rhs)
{
A tmp = *this;
*this = rhs;
rhs = tmp;
}
void swapMove(A& rhs)
{
A tmp = move(*this);
*this = move(rhs);
rhs = move(tmp);
}
};
class Widget
{
public:
template <typename T>
void
setA(T&& newA)
{
a = forward<T>(newA);
}
private:
A a;
};
int main()
{
Widget w;
A a;
// perfect forwarding
w.setA(a);
w.setA(A());
// A& operator=(const A&)
// A& operator=(A&&)
// move vs. copy
A a1, a2;
a1.swapCopy(a2);
a1.swapMove(a2);
// A(const A&)
// A& operator=(const A&)
// A& operator=(const A&)
// A(A&&)
// A& operator=(A&&)
// A& operator=(A&&)
}