【问题标题】:strange behaviour of this c++ piece of code (std::wcout and std::exception) [duplicate]这段 c++ 代码的奇怪行为(std::wcout 和 std::exception)[重复]
【发布时间】:2018-01-04 19:08: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 link to reproduce the lack of an exception with wcout. 和a link reproducing the exception when cout is used。

【问题讨论】:

    标签: c++ c++11 exception gcc std


    【解决方案1】:

    您的示例不证明没有引发异常。

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

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

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多