mardi 22 mai 2018

std::unique_ptr dereference exception not catch-ed in try-catch block

So lets say I have:

struct test {
    bool a;
    int b;
};

int main()
{
    std::unique_ptr<test> ptr;
    // don't init the ptr

    try
    {
        if (!ptr->a)
        {
            std::cout << "ok" << std::endl;
        }
    }
    catch (const std::exception &ex)
    {
        std::cout << "ex: " << ex.what() << std::endl;
    }

    return 1;
}

So here I setup a unique pointer, but I don't init it (to simulate this in a larger code base) but I want to catch the exception.

The problem is that my exception is not called - I just get a crash (memory access fault)

I read a few similar questions (but not quite the same) that suggested that I pass the exception by reference - but this did not work.

So is it possible to catch a unique_ptr de-reference exception?

EDIT: I should add that this is on Windows 7 box running MSVS2012 executable - incase it is relevant!

Aucun commentaire:

Enregistrer un commentaire