Should a function return a link or object?

Let's discuss these two functions:

  • complex & operator + = (const T & val);
  • complex operator + (const T & val);

Where "complex" is the name of the class that implements, for example, a complex variable.

So, the first operator returns a link so that you can write + = b + = c (which is equivalent to b = b + c; a = a + b;).

The second operator returns objec (NOT A REFERENCE), we can still write a = b + c + d.

Who could explain this nuance to me? What is the difference between a returned link or object?

+3
source share
5 answers

1, a + = b, + = a. , .

2. , a + b , a, a .

+1

:

(a += b) += c;

b, c a. , a += b a. , b + c + d . a .

+4

, , .

+ , : b + c b, c, - . , b c... , , . , .

, + = , .

+1

complex& operator+=(const T& val); this complex operator+(const T& val); .

+=, , , , , . , , . (a += b) += c, c , .

+, , undefined. a=b+c+d, b+c b1 b1 + d b2, a.

+1

In the first case, you add something to the object on the left, but the value of the expression is the object on the left. So you are returning something (usually left) by reference. For instance:

cout << (a+=b)

In the second case, you add two objects and get the third object, and you can do this calculation on the stack so that you return the actual object by value, not by reference. For instance:

if(...)
{
    T a = b + c;
    cout << a;
}
0
source

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


All Articles