Avatar ·

What is the "Rule of Three" in C++ and why does its absence cause memory leaks?

Hello everyone! I started learning C++ and encountered a problem. I'm writing a simple class that stores a string using dynamic memory. Everything seems logical, but the program crashes or behaves strangely. Here is my code: ```cpp class String { public: String(const char* str = "") { size = strlen(str); data = new char[size + 1]; strcpy(data, str); } ~String() { delete[] data; } private: char* data; int size; }; int main() { String s1("Hello"); String s2 = s1; // Copying String s3("World"); s3 = s1; // Assignment return 0; } ``` After running, the program crashes with a double free error. I understand that the problem is that when copying, both objects point to the same memory, but then...