What is a smart pointer and when should it be used?
Hello everyone! I recently started learning C++ and constantly encounter problems when working with memory. I'm especially scared of memory leaks and dangling pointers. For example, I often write code like this:
```cpp
class MyClass {
public:
int* data;
MyClass() {
data = new int(42);
}
~MyClass() {
delete data;
}
};
void example() {
MyClass* obj = new MyClass();
// ... some code that may throw an exception
delete obj;
}
```
The problem is that if an exception occurs between `new` and `delete`, or if I forget to call `delete`, memory leaks. And if someone deletes the object prematurely while I continue to use it, the program crashes.
I've heard that C++11 introduced "smart pointers" that are supposed to solve these issues.
No answers yet.
Log in to leave an answer