Memory overload operator?

The suggestion below: The positive legacy of C ++ and Java from Bruce Eckel, about operator overloading in C ++:

C ++ has both stack allocation and heap allocation, and you must overload operators to handle all situations and not cause memory leaks. It’s really difficult.

I do not understand how operator overloading has anything to do with memory allocation. Can someone explain how they correlate?

+3
source share
4 answers

I can present a couple of possible interpretations:

-, ++ new delete ; , , , .

-, operator=, . , (, Boost shared_ptr), operator=, , . :

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;
};

operator= , mData other.mData: mData, ; other.mData, , , , , .

, operator= , , , , .

, , , , .

EDIT: , , -, . , , , , , , , .

+3

new delete ++, , . .

+1

- . , , , . , member/global/friend.

, , -.

, operator+ operator+=. basic_string .

0

Java ++, new delete - Java .

- , .

, ++ .

, const , -, .

, ++, ( ) , new, ( , ), , .

, , .

- , . ++ , . , . , , ++. ( , , , , , , .) (, , , , , . ++)

The only duplication you get relates to cases like operator [], where the same operator is used as an accessory and a mutator. Then it's ok to have const and a non-constant version, so you can set the value if the receiver is not const. That’s good - the inability to mutate (generally accessible state) objects that have been marked permanent.

0
source

Source: https://habr.com/ru/post/1705314/


All Articles