C++ why the assignment operator should return a const ref in order to avoid (a=b)=c

后端 未结 5 1432
情书的邮戳
情书的邮戳 2020-11-30 04:16

I am reading a book about C++ and more precisely about the operator overloading.

The example is the following:

const Array &Array::operator=(cons         


        
5条回答
  •  一向
    一向 (楼主)
    2020-11-30 04:29

    I would look at the behavior of the built-in types.

    When defining your own types it is preferable that the operators behave the same way as the built-in types. This allows easy adoption of your classes without having to dig into your code to see why they behave differently from expected.

    So if we look at integers:

    int main()
    {
        int x = 5;
        int y = 6;
        int z = 7;
    
        (x = y) = z;
        std::cout << x << " " << y << " " << z << "\n";
    }
    

    This works with y unchanged and x being assigned 7. In your code i would expect your assignment operator to work the same way. The standard assignment operator definition:

    Array& Array::operator=(Array const& rhs)
    {
        /* STUFF */
        return *this;
    }
    

    Should do that just fine (assuming /* STUFF */ is correct).

提交回复
热议问题