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

后端 未结 5 1439
情书的邮戳
情书的邮戳 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:23

    As far as I know, assignment operators do not return const references in idiomatic C++. The Standard types do not return const references either.

    std::string a, b, c;
    (a = b).clear(); // no objection from compiler
    

    All of my custom assignment operators have returned a non-const reference.

    When in doubt, check the Standard library. It's not flawless, but it definitely gets basic things like this correct.

提交回复
热议问题