我尝试了以下代码:
#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;
}
当我编译并运行它时,它符合预期;一个无限循环。如果我删除友元函数中的 cout
语句,递归就不会发生。为什么会这样?
最佳答案
Optimizer 决定您所有剩余的事件都没有效果,并将其优化掉。 对与错是另一回事。
特别是:
X x;
创建空对象“x”
cout << x;
调用:
return (os << obj);
追加空对象;编译器注意到自上次调用以来“os”没有增长,并且没有显示任何进一步这样做的 promise (并且没有其他任何事情发生)所以它决定整个业务是多余的并且可以在此时被截断。
万一你打电话
cout << "hehe"; // comment this and infinite loop is gone
有一些额外的事件,因此优化器不会删除以下调用。
我想如果你初始化了 x
任何非空的,或执行除 cout << "hehe";
以外的任何非空事件,你会以同样的方式运行递归。
关于c++ - 重载 << 运算符和递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2355273/