Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overloading with memory allocation?

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?

like image 565
yesraaj Avatar asked Aug 31 '26 03:08

yesraaj


2 Answers

I can imagine a couple possible interpretations:

First, in C++ new and delete are 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 implement operator=, and you must be sure to do so correctly. Consider this broken example:

template <class T>
class RefCountedPtr {
public:
    RefCountedPtr(T *data) : mData(data) { mData->incrRefCount(); }
    ~RefCountedPtr() { mData->decrRefCount(); }
    RefCountedPtr<T>& operator=(const RefCountedPtr<T>& other) {
        mData = other.mData;
        return *this;
    }
    ...
protected:
    T *mData;
};

The operator= implementation here is broken because it doesn't manage the reference counts on mData and other.mData: it does not decrement the reference count on mData, leading to a leak; and it does not increment the reference count on other.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.

like image 195
Eric Melski Avatar answered Sep 01 '26 17:09

Eric Melski


new and delete are actually operators in C++ which you can override to provide your own customized memory management. Take a look at the example here.

like image 42
Naveen Avatar answered Sep 01 '26 17:09

Naveen