문제

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?

도움이 되었습니까?

해결책

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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top