Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator= return reference to *this

Look at the following code:

#include <iostream>
using namespace std;

class Widet{
public:
    Widet(int val = 0):value(val)
    {

    }

    Widet& operator=(Widet &rhs)
    {
        value = rhs.value;
        return *this;
    }
    int getValue()
    {
        return value;
    }
private:
    int value;
};

int main()
{
    Widet obj1(1);
    Widet obj2(2);
    Widet obj3(0);
    (obj3 = obj2) = obj1;
    cout << "obj3 = " << obj3.getValue() << endl;
}

The code runs successfully and the output is (using VS2008):

enter image description here

When I let the operator= return a value instead of reference:

Widet operator=(Widet &rhs)
{
    value = rhs.value;
    return *this;
}

It also runs successfully and the output is :

enter image description here

My question is :Why the second code runs well?Should not we get a error?

Why it is a good habit to return reference to *this instead of *this?

like image 661
XiaJun Avatar asked Aug 20 '12 13:08

XiaJun


People also ask

What does * this return?

this means pointer to the object, so *this is an object. So you are returning an object ie, *this returns a reference to the object. Save this answer.

What is return by reference in C?

Example: Return by Reference Unlike return by value, this statement doesn't return value of num , instead it returns the variable itself (address). So, when the variable is returned, it can be assigned a value as done in test() = 5; This stores 5 to the variable num , which is displayed onto the screen.

What is operator return value?

They can both be anything, but usually operator = returns the current object by reference, i.e. A& A::operator = ( ... ) { return *this; } And yes, "reference to the type of left hand operand" and "lvalue referring to left hand operand" mean the same thing. The dereference operator can have basically any return type.

What is operator return type?

The typeof operator returns a string indicating the type of the operand's value.


1 Answers

Why the second code runs well?Should not we get a error?

Because it's perfectly valid code. It returns a temporary copy of the object, and you're allowed to call member functions (including operator=()) on temporary objects, so there is no error.

You would get an error if the object were uncopyable.

Why it is a good habit to return reference to *this instead of *this?

Because not all objects are copyable, and some objects are expensive to copy. You can take a reference to any object, and references are always cheap to pass around.

like image 194
Mike Seymour Avatar answered Sep 30 '22 02:09

Mike Seymour