-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmoveassignmentoperator1.cpp
More file actions
64 lines (52 loc) · 1.71 KB
/
moveassignmentoperator1.cpp
File metadata and controls
64 lines (52 loc) · 1.71 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
// copy assignment operator=(const T& )
// move assignment operator=(T&& )
#include <iostream>
#include <cstring> // for strlen and strcpy
class MyString {
private:
char* data;
public:
// constructor
MyString(const char* str = ""){
data = new char[strlen(str) + 1];
strcpy(data, str);
}
// copy and move assignment operators almost always return *this by reference, i.e. the current object itself
// so the return type is T&
MyString& operator=(MyString&& other){ // other is a reference parameter, it refers to an existing MyString object
std::cout << "Move assignment called\n";
if (this != &other) { // this(keyword) is a pointer to the current object, so we need to take the reference of other(&other) to compare them
// free old memory
delete[] data;
// steal the pointer
data = other.data;
// set source to null
other.data = nullptr;
}
return *this;
}
~MyString() {
delete[] data;
}
void print() {
if (data)
std::cout << data << std::endl;
else
std::cout << "[empty]\n";
}
};
int main() {
MyString s1("Hello");
MyString s2("World");
s1.print();
s2.print();
s2 = std::move(s1);
s1.print();
s2.print();
return 0;
}
/* why do we need move assignment operator?
1. improves performance, it's faster than making a copy
2. reduces memory usage
3. handles temporary objects efficiently - it allows objects to take ownership of data from temporary values w/o copying
*/