c++ operator overloading memory question

后端 未结 6 2025
挽巷
挽巷 2021-01-01 07:44

In c++ you can create new instances of a class on both the heap and stack. When overloading an operator are you able to instantiate on the stack in a way that makes sense?

6条回答
  •  执念已碎
    2021-01-01 08:23

    If you're talking about for example operator+, where the object returned is not either of those input, then the answer is you instantiate on the stack and return by value:

    struct SomeClass {
        int value;
    };
    
    SomeClass operator+(const SomeClass &lhs, const SomeClass &rhs) {
        SomeClass retval;
        retval.value = lhs.value + rhs.value;
        return retval;
    }
    

    or

    class SomeClass {
        int value;
    public:
        SomeClass operator+(const SomeClass &rhs) const {
            SomeClass retval;
            retval.value = this->value + rhs.value;
            return retval;
        }
    };
    

    or even:

    class SomeClass {
        int value;
    public:
        SomeClass(int v) : value(v) {}
        friend SomeClass operator+(const SomeClass &lhs, const SomeClass &rhs) {
            return SomeClass(lhs.value + rhs.value);
        }
    };
    

    The compiler then worries about where (on the stack) the return value is actually stored.

    It will for example apply return-value optimizations if it can, but in principle what's happening is "as-if" the work you do constructs some value on the stack of your operator overload, and then at return this is copied to wherever it needs to be next. If the caller assigns the return value, it's copied there. If the caller passes it by value to some other function, it's copied wherever the calling convention says it needs to be in order to be that function parameter. If the caller takes a const reference, then it's copied to a temporary hidden away on the stack.

提交回复
热议问题