重载<<操作符和递归
-
23-09-2019 - |
题
我尝试以下代码:
#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
声明,递归不会发生。为什么会这样?
解决方案
优化决定所有剩余活动没有任何影响,并优化它拿走。 无论是对还是错则是另外一回事。
在特别是:
X x;
创建空对象 “X”
cout << x;
呼叫:
return (os << obj);
其是附加空对象;编译器通知“OS”自上次调用并没有任何增长,并显示没有答应这样做任何进一步的(和没有什么事情发生),所以它决定了整个业务是多余的,可以在此时被截断。
在的情况下调用
cout << "hehe"; // comment this and infinite loop is gone
有一些额外的活性,从而优化不会删除下面的调用。
我想如果你初始化x
与任何非空,或执行任何非空的活动比其他cout << "hehe";
,你必须递归运行一样。
其他提示
在这两种情况下(有和没有写入 “和合”)的Visual Studio中2005给出以下警告:
warning C4717: 'operator<<' : recursive on all control paths, function will cause runtime stack overflow
在这两种情况下它编译和在这两种情况下它给堆栈溢出。
然而,如果没有“和合”堆栈溢出发生位越快。
不隶属于 StackOverflow