Why are objects not cleared after hardware exception?

62 Views Asked by At

I am learning exception models in c++. Following example showed interesting result for me

#include <cstdio>

struct A
{
    A(int order) : m_order(order){}
    ~A(){printf("~A(%d)\n", m_order);}
    int m_order;
};

void foo(void)
{
    A a2 = 2;
    int i = 0;
    int j = 10 / i;
}

void foo1()
{
    A a1 = 1;
    foo();
}

void main()
{
    try
    {
        foo1();
    }
    catch (...)
    {
    }       
}

Result of execution of the program really depends on exception model.

For /EHa we have the output:

~A(2)
~A(1)

For /EHsc we have nothing.

As I understand, msvc c++ compiler internally uses SEH to support c++ exceptions. I thought that it will allow correctly call destructors of objects a1,a2 even in the case of hardware exceptions for both options (/EHa and /EHsc). But that example confuses me. It turns out that I should always use /EHa option to avoid possible memory leaks and corruptions in the case of hardware exceptions? But docs says that I should use /EHsc option whenever possible.

1

There are 1 best solutions below

2
MSalters On

The problem with /EHa is that it's not guaranteed to catch every possible problem, yet it comes with significant overhead. /EHsc is a lot more efficient, and still catches every throw.

As an example, MSVC++ may execute /0.0 using x87, SSE or AVX instructions, and the resulting hardware exception can differ. I have no idea when /EHa catches that.