Info |
---|
The "Rule of Three" is a guideline in C++ that states that if a class defines any of the following three special member functions, it should also define the other two:
|
The reason for the "Rule of Three" is to ensure that the class behaves correctly in all situations, and to avoid memory leaks or other problems that can arise from inconsistent memory management.
For example, if a class has a dynamically allocated memory resource that is managed by the constructor and destructor, it is important to define the copy constructor and copy assignment operator to properly handle copying the memory resource from one object to another. If these functions are not defined, the default implementations provided by the compiler may simply copy the pointer to the memory resource, resulting in two objects pointing to the same memory location. This can cause problems if one object is destroyed or modified, leaving the other object with a dangling pointer or invalid data.
...
Code Block | ||
---|---|---|
| ||
#include <iostream> #include <cstring> using namespace std; class String { private: char* buffer; public: // Default constructor - Initializes the buffer pointer to nullptr. String() : buffer(nullptr) {} // Parameterized constructor String(const char* str) { buffer = new char[strlen(str) + 1]; strcpy(buffer, str); } // Copy constructor String(const String& other) { buffer = new char[strlen(other.buffer) + 1]; strcpy(buffer, other.buffer); } // Copy assignment operator - takes a const String& parameter other // and checks for self-assignment. If this and other are different // objects, it deallocates the existing memory of buffer, // allocates new memory, and performs a deep copy of other buffer. String& operator=(const String& other) { if (this != &other) { delete[] buffer; buffer = new char[strlen(other.buffer) + 1]; strcpy(buffer, other.buffer); } return *this; } // Destructor ~String() { delete[] buffer; } // Getter function const char* getValue() const { return buffer; } }; int main() { String strOne("Hello"); String strTwo = strOne; // Copy construction String strThree("World"); strTwo = strThree; // Copy assignment cout << "strOne: " << strOne.getValue() << endl; cout << "strTwo: " << strTwo.getValue() << endl; cout << "strThree: " << strThree.getValue() << endl; return 0; } |
...
The given C++ code demonstrates the implementation of a simple String
class that manages dynamic memory allocation for storing character arrays. Here's a breakdown of the code:
...