-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmove_destructor.cpp
More file actions
78 lines (65 loc) · 1.62 KB
/
move_destructor.cpp
File metadata and controls
78 lines (65 loc) · 1.62 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
76
77
78
#include <string>
#include <iostream>
#include <utility>
#include <iomanip>
using namespace std;
struct A
{
string s;
int k;
A(): s("test"), k(-1) { }
A(const A& o): s(o.s), k(o.k) { cout << "move failed!\n"; }
A(A && o) noexcept :
s(move(o.s)),
k(exchange(o.k, 0))
{}
};
A f(A a)
{
return a;
}
struct B : A
{
string s2;
int n;
// implicit move constructur B::(B&&)
// calls A's move ctor
// calls s2's move constrctor
// and make a bitwise copy of n
};
struct C : B
{
~C() { } // destructor prevents implicit move ctor C::(C&&)
};
struct D : B
{
D() {}
~D() {} // destructor would prevent implicit move ctor D::(D&&)
D(D&&) = default; // forces a move ctor anyway
};
int main(int argc, char *argv[])
{
cout << "Trying to move A\n";
A a1 = f(A()); // return by value move-constructs the target from the function parameter
cout << "Befoer move, a1.s = " << quoted(a1.s) << " a1.k = " << a1.k << endl;
A a2 = move(a1); // move-constructs from xvalue
cout << " After move, a1.s = " << quoted(a1.s) << " a1.k = " << a1.k << endl;
cout << endl;
cout << "Trying to move B\n";
B b1;
cout << "Before move b1.s = " << quoted(b1.s) << endl;
B b2 = move(b1); // calls implicit move-ctor
cout << " After move, b1.s = " << quoted(b1.s) << endl;
cout << endl;
cout << "Trying to move C\n";
C c1;
C c2 = move(c1); // calls copy-ctor
cout << endl;
cout << "Trying to move D\n";
D d1;
cout << "Before move d1.s = " << quoted(d1.s) << endl;
D d2 = move(d1); // calls copy-ctor
cout << " After move, d1.s = " << quoted(d1.s) << endl;
cout << endl;
return 0;
}