Why should the assignment operator return a reference to the object?

妖精的绣舞 提交于 2019-11-26 09:09:54

问题


I\'m doing some revision of my C++, and I\'m dealing with operator overloading at the minute, specifically the \"=\"(assignment) operator. I was looking online and came across multiple topics discussing it. In my own notes, I have all my examples taken down as something like

class Foo
{
    public:  
        int x;  
        int y;  
        void operator=(const Foo&);  
};  
void Foo::operator=(const Foo &rhs)
{
    x = rhs.x;  
    y = rhs.y;  
}

In all the references I found online, I noticed that the operator returns a reference to the source object. Why is the correct way to return a reference to the object as opposed to the nothing at all?


回答1:


The usual form returns a reference to the target object to allow assignment chaining. Otherwise, it wouldn't be possible to do:

Foo a, b, c;
// ...
a = b = c;

Still, keep in mind that getting right the assigment operator is tougher than it might seem.




回答2:


The return type doesn't matter when you're just performing a single assignment in a statement like this:

x = y;

It starts to matter when you do this:

if ((x = y)) {

... and really matters when you do this:

x = y = z;

That's why you return the current object: to allow chaining assignments with the correct associativity. It's a good general practice.




回答3:


Your assignment operator should always do these three things:

  1. Take a const-reference input (const MyClass &rhs) as the right hand side of the assignment. The reason for this should be obvious, since we don't want to accidentally change that value; we only want to change what's on the left hand side.

  2. Always return a reference to the newly altered left hand side, return *this. This is to allow operator chaining, e.g. a = b = c;.

  3. Always check for self assignment (this == &rhs). This is especially important when your class does its own memory allocation.

    MyClass& MyClass::operator=(const MyClass &rhs) {
        // Check for self-assignment!
        if (this == &rhs) // Same object?
            return *this; // Yes, so skip assignment, and just return *this.
    
        ... // Deallocate, allocate new space, copy values, etc...
    
        return *this; //Return self
    }
    


来源:https://stackoverflow.com/questions/9072169/why-should-the-assignment-operator-return-a-reference-to-the-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!