Pergunta

I'm using Qt Creator 3.0.1 with MinGW 4.8 32-bit as the compiler.

When I put the following code into the very top of my main() function (before Qt does all its stuff), the output I get on the console is "std::exception", not "Whoops" as I would expect:

try {
    throw std::logic_error{"Whoops"};
}
catch (std::exception ex) {
    std::cout << ex.what() << std::endl;
}

I've also tried accessing what() through a pointer:

try {
    throw std::logic_error{"Whoops"};
}
catch (std::exception ex) {
    std::exception* ex2 = &ex;
    std::cout << ex2->what() << std::endl;
}

The exact same code compiled in VS2013 outputs "Whoops" as I would expect.

std::exception::what() is virtual, so why is this happening?

Foi útil?

Solução

As chris said, you're slicing the information. You can prevent this by catching a const reference instead (demo):

try {
    throw std::logic_error{"Whoops"};
} catch (const std::exception& ex) {
    std::cout << ex.what() << std::endl; // Whoops
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top