-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp-04.cpp
More file actions
78 lines (67 loc) · 1.93 KB
/
cpp-04.cpp
File metadata and controls
78 lines (67 loc) · 1.93 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 <iostream>
#include <utility>
#include <cstring>
class SmartClass {
private:
char* data;
public:
// Constructor
SmartClass(const char* str) {
data = new char[std::strlen(str) + 1];
std::strcpy(data, str);
std::cout << "Constructed: " << data << std::endl;
}
// Copy Constructor
SmartClass(const SmartClass& other) {
data = new char[std::strlen(other.data) + 1];
std::strcpy(data, other.data);
std::cout << "Copied: " << data << std::endl;
}
// Move Constructor
SmartClass(SmartClass&& other) noexcept : data(other.data) {
other.data = nullptr;
std::cout << "Moved (ctor): " << (data ? data : "null") << std::endl;
}
// Copy Assignment
SmartClass& operator=(const SmartClass& other) {
if (this != &other) {
delete[] data;
char* newData = new char[std::strlen(other.data) + 1];
std::strcpy(newData, other.data);
std::swap(data, newData);
}
std::cout << "Copy assigned: " << data << std::endl;
return *this;
}
// Move Assignment
SmartClass& operator=(SmartClass&& other) noexcept {
if (this != &other) {
delete[] data;
data = other.data;
other.data = nullptr;
}
std::cout << "Move assigned: " << (data ? data : "null") << std::endl;
return *this;
}
// Destructor
~SmartClass() {
std::cout << "Destroyed: " << (data ? data : "null") << std::endl;
delete[] data;
}
void print() const {
std::cout << "Data: " << (data ? data : "null") << std::endl;
}
};
int main() {
SmartClass a("Hello");
SmartClass b = a; // Copy
SmartClass c = std::move(a); // Move
SmartClass d("World");
d = b; // Copy assignment
d = std::move(c); // Move assignment
d.print();
b.print();
a.print();
c.print();
return 0;
}