防止cout打印的C ++异常

时间:2015-01-14 10:16:08

标签: c++ exception-handling cout

在以下代码中:

#include <iostream>
using namespace std;

int f()
{
    throw 1;
}

int main()
{
    try
    {
        cout << "Output: " << f() << endl;
    }
    catch (int x)
    {
        cout << x;
    }
}

为什么不打印"Output: "?不应该在operator<<(cout, "Output: ")之前调用operator<<(cout, f())吗?如果这条线是原子的,那么打印是如何反转的呢?

2 个答案:

答案 0 :(得分:7)

&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;运算符未在c ++标准中定义。看起来您的编译器在实际打印之前首先评估所有参数。

答案 1 :(得分:2)

考虑将实际的操作符函数调用组装为operator<<(operator<<(operator<<(cout, "Output:"), f()), endl)可能会有所帮助:然后您可以看到operator<<(cout, "Output:")f()只是另一个operator<<调用的两个函数参数。 1}}:不需要首先评估哪个函数参数。