How can we use an overloaded operator to prevent memory leaks in C++?
Any complete example..
Regards,
PKV
If you want to avoid memory leaks, don't use delete
.
It may seem paradoxical, but the truth is that manual memory management is error prone, it is best to use automatic (or library) technics.
In C++, for each object that you create, there should be a clear ownership. That is, you should be able to identify the object lifetime, possibly depending on some others.
The first step is to avoid dynamic memory allocation: if you do not use new
, you don't have anything to manage -- caveat: some library will hand you memory over and expect you to free it. Therefore, whenever possible, use the stack.
Many use of new
can be avoided by using the STL containers (std::vector<T>
for example) instead of rolling your own situations.
The second step is to use new
sparingly, and to always hand over the memory to a single owner immediately after it's been allocated. These owners include:
std::unique_ptr
(C++0x) or boost::scoped_ptr
, in a last resort std::auto_ptr
.boost::ptr_vector
and the whole collection of Boost.Pointer Container libraryA single owner is easy to track down, and since the object's lifetime is tied to its owner, therefore the object's lifetime is easy to track down too.
The third step is the delicate one, the introduction of shared ownership. It really complicates all reasoning around the object's lifetime, and introduces the risk of cycles of references, which effectively mean memory leaks. They are required in some situations, but best avoided whenever possible.
std::shared_ptr
(C++0x) or equivalent (std::tr1::shared_ptr
, boost::shared_ptr
)std::weak_ptr
(C++0x) or equivalentThe latter is used to "break" cycles. However it can quickly become difficult to understand where to introduce the weak_ptr
, even with a graph of the relationships.
EDIT:
As noted by Tobias, this idiom is known as Resources Acquisition Is Initialization (RAII), which is awkwardly named. A newer term is emerging: Scoped Bound Resources Management (SBRM) to describe a subset of it --> binding the resources to a scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With