0

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.

Alex Aparin
  • 4,393
  • 5
  • 25
  • 51
  • 1
    `/EHa` is a very expensive flag because it prevents many optimizations, such as dead store elimination. Any memory access could result in a hardware exception, so you have to spill before every memory access. Generally, you should just write your code so that hardware exceptions don't occur. (Or more accurately, assume that any hardware exception is fatal.) The C++ language itself does not require compilers to support unwinding on hardware exceptions. – Raymond Chen May 24 '21 at 03:41

1 Answers1

1

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • But example above shows that /Ehsc does not provide destruction of objects allocated on stack in the case of the hardware exception – Alex Aparin May 19 '21 at 14:27
  • @LmTinyToon: That is correct. But `/EHa` does not **guarantee** that either. So the advice is to treat `/0` as a bug, and fix it. – MSalters May 19 '21 at 14:29