3

this bit of code is driving me nuts:

#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;
}

Nothing crazy here. But the output ...

int 7675456

I tried it on my linux VM, on GDB online and repl-it and it's working fine. I mean I have what I expect:

string foo

I never post on here because I always find a solution. But this time, It looks that I can't figure out a correct way to ask google and I'm just lost. Anybody got a clue?

Windows 10 and I use MinGW

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
usePtr
  • 31
  • 2

1 Answers1

0

It's hard without an easy repro case, but try this: Move the

catch (const std::string &x)

to be BEFORE the catch for int.

What I suspect may be happening is that since it can somehow the string can be cast to an int, it is trying to do so. While this may not be a complete answer, at least you are a step closer to understanding what is going on, and now you have a workaround.

It is hard to debug something like this remotely, but if nothing else, it is a good exercise in critical logic and debugging approaches.

David Frenkel
  • 956
  • 7
  • 20
  • If I do that, it's working fine. The issue is that if I put that bloc there, it will catch any types too :D – usePtr May 22 '17 at 23:34
  • Ok, I tried the changing compiler solution. I just renamed my MinGW folder and used Perl's C compiler (I just discovered that it had one). It's working fine. So I guess I could just download a fresh copy of MinGW 64 and everything gonna be alright. – usePtr May 22 '17 at 23:38
  • https://bugzilla.redhat.com/show_bug.cgi?id=1269290 may be (related to) the root cause. – Jakub May 23 '17 at 12:08
  • Yeah, so somehow your compiler was indeed casting that string & into an int. I'd call that "understandable, but definitely not expected" behavior. – David Frenkel May 26 '17 at 00:38