重载<<运算符和递归

leg*_*s2k 5 c++ recursion cout operator-overloading ostream

我尝试了以下代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

当我编译并运行它时,它就像预期的那样; 无限循环.如果我删除cout友元函数中的语句,则不会发生递归.为什么会这样?

SF.*_*SF. 7

优化程序会决定您的所有剩余活动无效并将其优化.无论是对还是错都是另一回事.

特别是:

X x;
Run Code Online (Sandbox Code Playgroud)

创建空对象"x"

cout << x;
Run Code Online (Sandbox Code Playgroud)

要求:

return (os << obj);
Run Code Online (Sandbox Code Playgroud)

附加空对象; 编译器通知'os'自上次调用以来没有增长任何进展,并且没有任何进一步的承诺(并且没有其他任何事情发生),所以它决定整个业务是多余的,并且此时可以被截断.

如果你打电话

    cout << "hehe";          // comment this and infinite loop is gone
Run Code Online (Sandbox Code Playgroud)

还有一些额外的活动,因此优化器不会删除以下调用.

我想如果你x用非空的任何东西初始化,或者执行除了之外的任何非空活动cout << "hehe";,你的递归运行都是一样的.


Pat*_*ick 6

在这两种情况下(使用和不使用"hehe"),Visual Studio 2005都会发出以下警告:

warning C4717: 'operator<<' : recursive on all control paths, function will cause runtime stack overflow
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,它都会编译,在这两种情况下都会产生堆栈溢出.

但是,如果没有"hehe",堆栈溢出会更快发生.