I'm going to give this a firm "very possibly".
One form of memory leak is when a function allocates memory and doesn't delete it in at least one path out of the function. Some sort of scoped pointer, like auto_ptr
, might handle this very well. (Note: auto_ptr
was part of the first ISO standard, and is being deprecated in the next one, so it's hard to give advice on what scoped pointer to use. Consult your compiler and library documentation to see what they support.)
Another form is where an object is allocated, and ownership is shared, meaning that there's more than one routine that uses it and no easy way to tell if everybody's through with it. This is a good candidate for shared_ptr
, but you have to use some care. Assign to a shared_ptr
when you create the object, and make sure that every other pointer use is a shared_ptr
. If routines A, B, and C access the object through a shared_ptr
, and you didn't change D, then when routines A, B, and C are through with it it goes away, regardless of D's needs.
One thing you want to avoid with shared_ptr
is cycles, since if I has a shared_ptr
to J, J has a shared_ptr
to K, and K has a shared_ptr
to I, none of those are ever going to be deleted, even if unreachable from anywhere else in the program. You need to watch for those situations. You can break them up with a weak_ptr
in the cycle, or delete an element in the cycle yourself, or just live with the leak.
Another thing to consider is substituting vector
and similar containers for dynamically allocated arrays and other dynamically allocated data structures. This gives you a lot of memory management for free, although you can still leak memory. If a vector grows large, and then becomes small, it will not release the extra memory. The usual practice, if you really need to reclaim memory, is to swap
the once-large vector with a copy of itself.
In short, there's a lot of very useful tools to automate a lot of memory management, but they don't replace thinking on your part. A lot of issues can be solved by just turning each pointer into a shared_ptr
and each array into a vector
, but using those intelligently will give even greater benefits.