The sentence below is from, The Positive Legacy of C++ and Java by Bruce Eckel, about operator overloading in C++:
C++ has both stack allocation and heap
allocation and you must overload your
operators to handle all situations and
not cause memory leaks. Difficult
indeed.
I do not understand how operator overloading has anything to do with memory allocation. Can anyone please explain how they are correlated?
I can imagine a couple possible interpretations:
First, in C++
newanddeleteare both actually operators; if you choose to provide custom allocation behavior for an object by overloading these operators, you must be very careful in doing so to ensure you don’t introduce leaks.Second, some types of objects require that you overload
operator=to avoid memory management bugs. For example, if you have a reference counting smart pointer object (like the Boost shared_ptr), you must implementoperator=, and you must be sure to do so correctly. Consider this broken example:The
operator=implementation here is broken because it doesn’t manage the reference counts onmDataandother.mData: it does not decrement the reference count onmData, leading to a leak; and it does not increment the reference count onother.mData, leading to a possible memory fault down the road because the object being pointed to could be deleted before all the actual references are gone.Note that if you do not explicitly declare your own
operator=for your classes, the compiler will provide a default implementation which has behavior identical to the implementation shown here — that is, completely broken for this particular case.So as the article says — in some cases you must overload operators, and you must be careful to handle all situations correctly.
EDIT: Sorry, I didn’t realize that the reference was an online article, rather than a book. Even after reading the full article it’s not clear what was intended, but I think Eckel was probably referring to situations like the second one I described above.