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

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

本文关键字:std wcout exception 代码 C++ 这段      更新时间:2023-10-16

我正在使用这段代码,我发现该方法在成功调用后不会引发异常。如果我使用 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 链接,用于重现缺少异常wcout.以及一个在使用cout时重现异常的链接。

您的示例不能证明未引发异常。

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

cout更改为wcout,您将看到引发异常,只是没有看到预期的消息