这段 C++ 代码的奇怪行为(std::wcout 和 std::exception)

strange behaviour of this c++ piece of code (std::wcout and std::exception)

我正在处理这段代码,我发现该方法在成功调用后不会抛出异常。如果我使用 std::cout 一切都很好并且抛出异常。我正在使用 gcc 4.9.2 版(Debian 4.9.2-10)。它是 gcc 错误还是 stl 错误代码问题还是其他什么?

// exceptions
#include <iostream>
using namespace std;
class C {
   public:
    string srch(int &i) {
        if (i == 0) {   //found
            wcout << "got it: " << i << endl; return "i";
        }
       throw std::exception();

    }

 };

 int main () {
   C c = C();
   int i = 2;
   int j = 0;
   try
   {
     c.srch(j);
     c.srch(i);
   }
   catch (const std::exception &e) {
     cout << "An exception occurred. Exception Nr. " << e.what() << '\n';
   }
    return 0;
 }

这是一个 ideone link to reproduce the lack of an exception with wcout. and a link reproducing the exception when cout is used

你的例子没有证明没有抛出异常。

您的 catch 块中的 cout 消息未显示,因为您已经使用 wcout 并且在同一设备 (stdout) 上混合字符宽度是未定义的行为。

cout 更改为 wcout,您将看到抛出异常 was,您只是没有看到预期的消息。