Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

assignment operator return a reference to *this in C++

I read about this from "Effective c++" ,this is Col.10. It say it's a good way to have assignment operators return a reference to *this. I wrote a code snippet to test this idea. I overridden the assignment operator here.And tested it. Everything is fine. But when I remove that operator overriding, everything is the same. That means, the chaining assignment still works well. So, what am I missing? Why is that? Need some explanation from you guys, THank you.

#include <iostream>

using namespace std;

class Widget{
public:

    Widget& operator=(int rhs)
    {
        return *this;
    }
    int value;

};

int main()
{
    Widget mywidget;
    mywidget.value = 1;
    Widget mywidget2;
    mywidget2.value = 2;
    Widget mywidget3 ;
    mywidget3.value = 3;
    mywidget = mywidget2 = mywidget3;
    cout << mywidget.value<<endl;
    cout << mywidget2.value<<endl;
    cout << mywidget3.value<<endl;

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you remove completely the operator= method, a default operator= will be created by the compiler, which implements shallow copy1 and returns a reference to *this.

Incidentally, when you write

mywidget = mywidget2 = mywidget3;

you're actually calling this default operator=, since your overloaded operator is designed to work with ints on the right side.

The chained assignment will stop working, instead, if you return, for example, a value, a const reference (=>you'll get compilation errors) or a reference to something different from *this (counterintuitive stuff will start to happen).

Partially related: the copy and swap idiom, i.e. the perfect way to write an assignment operator. Strongly advised read if you need to write an operator=


  1. The default operator= will perform as if there were an assignment between each member of the left hand operand and each member of the right hand one. This means that for primitive types it will be a "brutal" bitwise copy, which in 90% of cases isn't ok for pointers to owned resources.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...