I have been learning about the heap and avoiding memory leaks.
void foo();
void test()
{
int* p = new int(24);
foo();
delete p;
}
Question: is the above code leak free?
Answer: No!! And whoever or whatever is teaching you that to avoid memory leaks you need to use delete
is teaching you very very bad C++ programming. The above code will leak if foo()
throws.
The only solution is to use RAII whenever you need to manage ownership of resources (like you do when you allocate memory). For this use smart pointers or higher abstractions like containers (std::vector
etc).
So since almost always new
/delete
in user code is a bug there aren't tools to help you write new
/delete
.