-
Notifications
You must be signed in to change notification settings - Fork 0
/
move_semantics.cpp
66 lines (52 loc) · 1.21 KB
/
move_semantics.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
// Move Semantics C++ 11/14
#include <utility>
using namespace std;
struct Foo {
Foo() = default;
Foo(int i )
: i(new int(i))
{}
Foo(Foo const& other) {
if(other.i != nullptr) {
i = new int(*other.i);
}
}
Foo& operator=(Foo const& other) {
if (other.i != nullptr) {
// i = new int(*other.i);
}
return *this;
}
// Overwriting copy operator
Foo& operator=(Foo&& other) { // rvalue reference
if (other.i != nullptr) {
i = other.i;
other.i = nullptr;
}
return *this;
}
~Foo() {
delete i;
i = nullptr;
}
int * i = nullptr;
};
template <typename T, typename U>
bool Equals(T lhs, U rhs) {
return lhs == rhs;
}
void FuncByValue(Foo other); // value semantics
void FuncByRef(Foo& other); // reference semantics
int ReturnPRvalue() { return 42;}
int main() {
Foo f1;
int i = ReturnPRvalue();
{
Foo f2;
f2.i = new int(42);
// Move treats f2 as an expiring value, we
// explicitly tell the compiler that f2 is going to go out of scope
// f1 = move(f2); // xvalue
f1 = Foo(42); // prvalue
}
}