I remember intervening "in urgence" on an application that was leaking badly:
- the improvements needed to be loaded quickly
- the application was already leaking, though less badly
- the non-regressions were known to be incomplete
- the application had never run under valgrind (it's not trivial to run multi-threaded code with tight timeout dependencies under valgrind...)
So, what did I do ? I used grep
and removed all calls to new
from the code (*).
- in C++03:
delete
is an error (**) andnew
is a code smell - in C++11: both
delete
andnew
are an error (**)
And not so surprisingly, all memory leaks disappeared!
Instead of using new, you can use:
std::vector
for a dynamically allocated arraystd::unique_ptr
for a dynamically allocated objectstd::shared_ptr
in some rare and arcane situations where the actual lifetime of an object obeys complex rules(*) or I could have if it had been C++11, in C++03 and in the absence of perfect-forwarding and variadic templates having a
make_auto_ptr
was not really possible.(**) in C++03 it could be argued that an expert writing
boost::scoped_ptr
(or equivalent) might need it; in C++11 you can build about every abstraction on top ofunique_ptr
because it's 0-cost.