Why do some class methods return "* this" (object reference to themselves)?

There are many explanation codes on the Internet (also specifically here in stackoverflow) that return *this .

For example, from post Copy constructor and = operator overloading in C ++: is a generic function possible? :

 MyClass& MyClass::operator=(const MyClass& other) { MyClass tmp(other); swap(tmp); return *this; } 

When I write swap as:

 void MyClass::swap( MyClass &tmp ) { // some code modifying *this ie copying some array of tmp into array of *this } 

Is it not enough to set the return value from operator = to void and not return *this ?

+5
source share
3 answers

This idiom exists to enable a chain of function calls:

 int a, b, c; a = b = c = 0; 

This works well for int s, so it makes no sense to do this not for custom types :)

Similarly for stream operators:

 std::cout << "Hello, " << name << std::endl; 

works the same way

 std::cout << "Hello, "; std::cout << name; std::cout << std::endl; 

Due to the idiom return *this , you can link as the first example.

+8
source

One of the reasons why *this returns to allow destination chains, such as a = b = c; , which is equivalent to b = c; a = b; b = c; a = b; . In general, the result of an assignment can be used anywhere, for example. when calling functions ( f(a = b) ) or in expressions ( a = (b = c * 5) * 10 ). Although, in most cases, this just makes the code more complex.

+7
source

you return *this when there is a strong feeling that you will invoke another action for the object.

for example, std::basic_string::append returns itself because there is a strong feeling that you want to add another line

str.append("I have ").append(std::to_string(myMoney)).append(" dollars");

same for operator =

myObj1 = myObj2 = myObj3

swap doesn't have that much meaning. Does obj.swap(other).swap(rhs) really seem to be common?

0
source

Source: https://habr.com/ru/post/1246941/


All Articles