-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmove_semantics.cpp
118 lines (98 loc) · 2.37 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
#include <cstring>
using namespace std;
// Basically, move_semantics is the single,
// biggest use case of r-value-references.
// We use move_sematics to optimize out c++ code.
// Nothing else.
// Generally speaking, move_semantics allows us to "move",
// objects around.
// This was not possible before C++11, because,
// there was no r-value-reference.
// The basic idea is that when we are writing C++
// code, then there are many cases when we do not
// want to copy objects from one place to another.
// But, before move_semantics, that was the only way
// to get an object from one place to another.
// Move semantics allows us to "move" an object
// instead of creating a new copy inside memory.
// That's the biggest advantage.
// For eg. to get an object inside a function, I first
// have to create a copy of that object inside the
// function. And then I can get the data.
// creating a class
class String
{
public:
String() = default;
String(const char *string)
{
printf("Created!\n");
m_size = strlen(string);
m_data = new char[m_size];
memcpy(m_data, string, m_size);
}
String(const String &other)
{
printf("Copied!\n");
m_size = other.m_size;
m_data = new char[m_size];
memcpy(m_data, other.m_data, m_size);
}
// move constructor
String(String &&other)
{
printf("Moved!\n");
m_size = other.m_size;
m_data = other.m_data;
other.m_size = 0;
other.m_data = nullptr;
}
~String()
{
cout << "Destroyed!" << endl;
delete[] m_data;
}
void Print()
{
for (int i = 0; i < m_size; i++)
{
printf("%c", m_data[i]);
}
cout << endl;
}
private:
char *m_data;
int m_size;
};
class Entity
{
public:
Entity(const String &name)
: m_name(name)
{
}
// move constructor.
Entity(String &&name)
// we have to explicitly define the
// move constructor.?
// We can typecase the object or use
// move()
// : m_name(move(name))
: m_name((String &&) name)
{
}
void printName()
{
m_name.Print();
}
private:
String m_name;
};
int main()
{
// Entity entity(String("Aryan"));
Entity entity("Aryan");
entity.printName();
// std::cin.get();
}