Why should operator overload << be returned by reference?

I want to print an object of a user-defined type, for example cout << ob1; so I want to overload the operator <<and I want to return by value not by reference, but it gives me an error: in two files named: iosfwd and ios_base.h

 ostream operator<<( ostream& out, cat& rhs){ out << rhs.a << ", " << rhs.b << endl; return out ; } 

1) Is it because it cannot create a new ostream object, so should it return by reference?

but when I return the link as follows:

 ostream& operator<<( ostream& out, cat& rhs){ out << rhs.a << ", " << rhs.b << endl; return out ; } 

It works great.
2) any explanation?

+5
source share
3 answers

In the first example, you return a copy of the stream object that is not allowed, because the copy constructors (and also the copy destination) of all stream classes in C ++ were disabled due to the presence they made private .

Since you cannot make a copy of the stream object, you need to return it by reference, which you do in the second example, so it works fine.

You can return nothing at all (i.e. you can make the return type void ), but if you do, you cannot connect like stream << a << b . You must write them separately as stream <<a and then stream << b .

If you want to know why streaming object copying is disabled, see my answer here:

+14
source

Streams are not copied, because copying a stream does not really make sense, the stream is unique (you cannot jump into the same river twice). return by value is in C ++ 03, at least copying the transaction.

If there is a reason why you want to return by value, return the correct version via the link.

+2
source

This is done to support a safe and reasonable chain of operators, such as

  cout<<a<<b; 

works due to link return.

0
source

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


All Articles