return value of operator overloading in C++

前端 未结 5 2090
逝去的感伤
逝去的感伤 2020-11-29 18:19

I have a question about the return value of operator overloading in C++. Generally, I found two cases, one is return-by-value, and one is return-by-reference. So what\'s the

5条回答
  •  清酒与你
    2020-11-29 18:31

    To attempt an answer to your question regarding strings, the operator+() for strings is almost always implemented as a free (non-member) function so that implicit conversions can be performed on either parameter. That is so you can say things like:

    string s1 = "bar";
    string s2 = "foo" + s1;
    

    Given that, and that we can see that neither parameter can be changed, it must be declared as:

    RETURN_TYPE operator +( const string & a, const string & b );
    

    We ignore the RETURN_TYPE for the moment. As we cannot return either parameter (because we can't change them), the implementation must create a new, concatenated value:

    RETURN_TYPE operator +( const string & a, const string & b ) {
        string newval = a;
        newval += b;    // a common implementation
        return newval;
    }
    

    Now if we make RETURN_TYPE a reference, we will be returning a reference to a local object, which is a well-known no-no as the local object don't exist outside the function. So our only choice is to return a value, i.e. a copy:

    string operator +( const string & a, const string & b ) {
        string newval = a;
        newval += b;    // a common implementation
        return newval;
    }
    

提交回复
热议问题