How can we use an overloaded operator to prevent memory leaks in C++?
Any complete example..
Regards,
PKV
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
newcan be avoided by using the STL containers (std::vector<T>for example) instead of rolling your own situations.The second step is to use
newsparingly, 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) orboost::scoped_ptr, in a last resortstd::auto_ptr.boost::ptr_vectorand 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.