forked from nesteruk/ModernCpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MoveRvalue.cpp
67 lines (52 loc) · 1.1 KB
/
MoveRvalue.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
#include "Headers.h"
string getName()
{
return "Dmitri";
}
void printName(const string& name) // refers to a permanent object
{
cout << "Ordinary reference: " << name << endl;
}
void printName(string&& name) // refers to a temp object
{
cout << "Rvalue reference: " << name << endl;
}
class Widget {
public:
Widget() { cout << "Widget ctor" << endl; }
Widget(Widget&& w)
{
cout << "Widget move ctor" << endl;
}
~Widget() {
cout << "Widget destructor" << endl;
}
};
int main()
{
// RVALUE REFERENCES
// this is ok
string name1 = getName();
// not ok because expression must be lvalue
//string& name2 = getName();
// this is just bizarre
getName() = "Ann";
// this is legit
const string& name3 = getName();
// but try compiling this
//name3 = "John";
string&& name4 = getName();
name4 = "Jack";
cout << name4 << endl;
// so now what we can do is
string j{"John"};
printName(getName());
printName(j);
// MOVE SEMANTICS
cout << endl << "=== Putting widget into vector ===" << endl;
vector<Widget> widgets;
Widget w;
//widgets.push_back(w);
//widgets.emplace_back(w);
return 0;
}