fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. class Demo {
  7. private:
  8. std::string* name; // Pointer to a string to demonstrate deep copying
  9.  
  10. public:
  11. // Constructor
  12. Demo(const std::string& n = "") : name(new std::string(n)) {
  13. std::cout << "Constructor called for: " << *name << std::endl;
  14. }
  15.  
  16. // Copy Constructor
  17. Demo(const Demo& other) : name(new std::string(*other.name)) {
  18. std::cout << "Copy Constructor called for: " << *name << std::endl;
  19. }
  20.  
  21. // Move Constructor
  22. Demo(Demo&& other) noexcept : name(other.name) {
  23. other.name = nullptr; // Transfer ownership
  24. std::cout << "Move Constructor called" << std::endl;
  25. }
  26.  
  27. // Copy Assignment Operator
  28. Demo& operator=(const Demo& other) {
  29. if (this == &other) return *this; // Self-assignment check
  30. delete name; // Clean up current resource
  31. name = new std::string(*other.name); // Deep copy
  32. std::cout << "Copy Assignment Operator called for: " << *name << std::endl;
  33. return *this;
  34. }
  35.  
  36. // Move Assignment Operator
  37. Demo& operator=(Demo&& other) noexcept {
  38. if (this == &other) return *this; // Self-assignment check
  39. delete name; // Clean up current resource
  40. name = other.name; // Transfer ownership
  41. other.name = nullptr; // Nullify source pointer
  42. std::cout << "Move Assignment Operator called" << std::endl;
  43. return *this;
  44. }
  45.  
  46. // Destructor
  47. ~Demo() {
  48. if (name) {
  49. std::cout << "Destructor called for: " << *name << std::endl;
  50. } else {
  51. std::cout << "Destructor called for: null" << std::endl;
  52. }
  53. delete name;
  54. }
  55.  
  56. // Utility function to display the name
  57. void display() const {
  58. if (name) {
  59. std::cout << "Name: " << *name << std::endl;
  60. } else {
  61. std::cout << "Name: null" << std::endl;
  62. }
  63. }
  64. };
  65.  
  66.  
  67. Demo buildObj(string s) {
  68. cout << "buildObj" << endl;
  69. return Demo(s);
  70. }
  71.  
  72. int main() {
  73.  
  74. /*
  75.   Demo d1("Object1"); // Constructor
  76.   Demo d2 = d1; // Copy Constructor
  77.   Demo d3("Object2");
  78.   d3 = d1; // Copy Assignment Operator
  79.   Demo d4 = std::move(d1); // Move Constructor
  80.   Demo d5("Object3");
  81.   d5 = std::move(d2); // Move Assignment Operator
  82. */
  83. Demo d1 = buildObj("Object1");
  84. Demo *d1_ptr = new Demo(std::move(d1));
  85. delete d1_ptr;
  86.  
  87. return 0;
  88. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
buildObj
Constructor called for: Object1
Move Constructor called
Destructor called for: Object1
Destructor called for: null