Overload << statement and recursion

I tried the following code:

#include <iostream>
using std::cout;
using std::ostream;

class X
{
public:
    friend ostream& operator<<(ostream &os, const X& obj) 
    {
        cout << "hehe";          // comment this and infinite loop is gone
        return (os << obj);
    }
};

int main()
{
    X x;
    cout << x;
    return 0;
}

When I compile and run this, it is as expected; endless cycle. If I delete the statement coutinside the friend function, recursion will not happen. Why is this so?

+5
source share
2 answers

The optimizer decides that all remaining actions do not affect and optimize it. Right or wrong is another matter.

In particular:

X x;

creates an empty x

cout << x;

calls:

return (os << obj);

; "os" ( ), , .

    cout << "hehe";          // comment this and infinite loop is gone

, .

, x - , cout << "hehe";, , .

+7

( "-" ) Visual Studio 2005 :

warning C4717: 'operator<<' : recursive on all control paths, function will cause runtime stack overflow

, .

"-" .

+6

All Articles