If you want to avoid memory leaks, do not use delete .
This may seem paradoxical, but the truth is that manual memory management is error prone, it is better to use an automatic (or library) technique.
In C ++, there must be a clear ownership right for each object created. That is, you should be able to identify the lifetime of an object, possibly depending on some others.
The first step is to avoid allocating dynamic memory: if you are not using new , you have nothing to get around - caveat: some library will give you memory and expects you to free it. Therefore, whenever possible, use the stack .
Much use of new can be avoided by using STL containers (e.g. t23>) instead of translating your own situations.
The second step is to use new sparingly and always transfer memory to one owner immediately after allocating it. These owners include:
One owner is easy to track, and since the lifetime of an object is tied to its owner, so the lifetime of an object is also easily tracked.
The third step is the delicate, introduction of shared ownership. This really complicates all discussions about the lifetime of an object and introduces the risk of link cycles, which actually means a memory leak. They are required in some situations, but best avoided when possible.
std::shared_ptr (C ++ 0x) or equivalent ( std::tr1::shared_ptr , boost::shared_ptr )std::weak_ptr (C ++ 0x) or equivalent
The latter is used to break cycles. However, it quickly becomes difficult to figure out where to enter weak_ptr , even with a relationship graph.
EDIT:
As Tobias noted, this idiom is known as Resource Initialization (RAII), which is awkwardly named. A new term appears: limited resource management (SBRM) to describe a subset of it β resource binding to a domain.