Why C++ programmers should minimize the use of `new`
Hello, colleagues! I'm a beginner C++ developer trying to understand best practices. Everywhere I read that I should avoid `new`, but I don't fully understand the reason. In textbooks they often write: "allocate memory on the heap using `new`", and then experienced developers say: "don't do that". This confuses me.
Here's a simple example: I need to create an object that will live longer than the current function. I write:
```cpp
class MyClass {
public:
MyClass() { std::cout << "Created\n"; }
~MyClass() { std::cout << "Destroyed\n"; }
void doWork() { /* ... */ }
};
void process() {
MyClass* obj = new MyClass();
obj->doWork();
// Forgot delete! Memory leak.
}
```
Problem: I often forget to call `delete`, and this leads to memory leaks. I've also heard that `new` can throw exceptions...