I know about new and delete. Why shuldn't I use them? |
Because there are safer, better alternatives. In your code above, you made a memory leak. As code gets more complicated, this gets easier and easier to do, and then when we throw exceptions into the mix, it becomes even easier. Using new and delete is a way to significantly increase the chances of making mistakes. Even if you get it right, in five years' time a successor programmer will add one new pathway, one new case, and in some place fifty files over where a delete becomes necessary, it won't be added and your code starts leaking five years after you left it in working condition. This happens every day in industry with full-time C++ programmers :/
The question isn't why
shouldn't you use them; the question is why
should you use them? You need a good reason to use new and delete instead of the safer, better alternatives (such as on the stack, containers, and smart pointers with make_unique and make_shared).
Good reasons do exist, but the default you reach for when you need dynamic memory shouldn't be new and delete. As a beginner, where simple, easy to remember rules are more helpful than lists of cases and considerations, a simple rule that covers most cases is "don't".
Yes, if you always used them perfectly, you could use them all the time without any trouble. No such programmer has ever existed.