What is the "Rule of Three" in C++ and why does violating it lead to memory leaks?
Hi! I started learning C++ and encountered an unclear error. I have a class `SimpleString` that stores a dynamic string. I wrote a constructor and destructor, but when I try to copy an object or assign one object to another, the program crashes or outputs garbage. Here's an example code:
```cpp
#include
#include
class SimpleString {
public:
char* data;
SimpleString(const char* str) {
data = new char[strlen(str) + 1];
strcpy(data, str);
std::cout << "Constructed: " << data << std::endl;
}
~SimpleString() {
delete[] data;
std::cout << "Destructed" << std::endl;
}
};
int main() {
SimpleString a("Hello");
SimpleString b = a; // Copying
SimpleString c("World");
No answers yet.
Log in to leave an answer
Blogs
New Life of Strings in Swift: Goodbye, substring, Hello, Slicing
C# vs Python for Backend: What Should a Beginner Choose in 2024
Arrays of Objects in TypeScript: A Complete Guide with Examples
Converting a String to a Stream in C#: A Guide for Beginners