#include <iostream>
#include <string>
using namespace std;
class Demo {
private:
std::string* name; // Pointer to a string to demonstrate deep copying
public:
// Constructor
Demo(const std::string& n = "") : name(new std::string(n)) {
std::cout << "Constructor called for: " << *name << std::endl;
}
// Copy Constructor
Demo(const Demo& other) : name(new std::string(*other.name)) {
std::cout << "Copy Constructor called for: " << *name << std::endl;
}
// Move Constructor
Demo(Demo&& other) noexcept : name(other.name) {
other.name = nullptr; // Transfer ownership
std::cout << "Move Constructor called" << std::endl;
}
// Copy Assignment Operator
Demo& operator=(const Demo& other) {
if (this == &other) return *this; // Self-assignment check
delete name; // Clean up current resource
name = new std::string(*other.name); // Deep copy
std::cout << "Copy Assignment Operator called for: " << *name << std::endl;
return *this;
}
// Move Assignment Operator
Demo& operator=(Demo&& other) noexcept {
if (this == &other) return *this; // Self-assignment check
delete name; // Clean up current resource
name = other.name; // Transfer ownership
other.name = nullptr; // Nullify source pointer
std::cout << "Move Assignment Operator called" << std::endl;
return *this;
}
// Destructor
~Demo() {
if (name) {
std::cout << "Destructor called for: " << *name << std::endl;
} else {
std::cout << "Destructor called for: null" << std::endl;
}
delete name;
}
// Utility function to display the name
void display() const {
if (name) {
std::cout << "Name: " << *name << std::endl;
} else {
std::cout << "Name: null" << std::endl;
}
}
};
Demo buildObj(string s) {
cout << "buildObj" << endl;
return Demo(s);
}
int main() {
/*
Demo d1("Object1"); // Constructor
Demo d2 = d1; // Copy Constructor
Demo d3("Object2");
d3 = d1; // Copy Assignment Operator
Demo d4 = std::move(d1); // Move Constructor
Demo d5("Object3");
d5 = std::move(d2); // Move Assignment Operator
*/
Demo d1 = buildObj("Object1");
Demo *d1_ptr = new Demo(std::move(d1));
delete d1_ptr;
return 0;
}