c++ - first catch 捕获任何类型

标签 c++ c++11 exception-handling mingw catch-block

这段代码让我抓狂:

#include<iostream>
#include<string>

int main()
{
    std::string test = "foo";
    try
    {
        throw test;
    }
    catch (const int &x)
    {
        std::cout << "int " << x << "\n";
    }
    catch (const double &x)
    {
        std::cout << "double " << x  << "\n";
    } 
    catch (const std::string &x)
    {
        std::cout << "string " << x  << "\n";
    }  
    return 0;
}

这里没有什么疯狂的。但是输出...

int 7675456

我在我的 Linux 虚拟机上、在线 GDB 和 repl-it 上试过了,它工作正常。我的意思是我有我所期望的:

string foo

我从不在这里发帖,因为我总能找到解决方案。但是这一次,看起来我无法找到正确的方法来询问谷歌,我只是迷路了。有人知道吗?

Windows 10 和我使用 MinGW

最佳答案

如果没有一个简单的重现案例就很难,但试试这个: 移动

catch (const std::string &x)

在捕获 int 之前。

我怀疑可能发生的情况是,由于它可以以某种方式将字符串转换为 int,因此它正在尝试这样做。虽然这可能不是一个完整的答案,但至少您离理解正在发生的事情又近了一步,现在您有了解决方法。

很难远程调试这样的东西,但如果不出意外,这是对关键逻辑和调试方法的很好练习。

关于c++ - first catch 捕获任何类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44123288/

相关文章:

c++ - 为什么编译器可以比普通函数更好地优化 lambda?

c++ - 使用可变参数模板制作类似元组的编译时 "linked-list"

exception - 为什么抛出异常比返回错误代码更好?

c++ - 如何在 system() 调用中使用 std::string 作为命令?

c++ - 多态性是否适用于值?或者在按(基)值返回时使用派生类的 move 构造函数

c++ - 正确删除 с++ 中的类

c# - ASP.NET (C#) Web 服务中的异常处理

c++ - srand (time (null)) 导致编译器警告 : implicit conversion loses integer precision

c++ - 为什么 std::multimap 没有 [] 运算符?

php - 为生产覆盖 Kohana_Exception::_handler() - 3.3