Why don't my destructors get called when throwing from win32 timer callback?

I just asked this question . In short, when you throw from the win32 timer callback, the exception does not appear anywhere. It seems to be stealthily handled by Windows somewhere.

Ok, this is a problem. The other side of the problem is that destructors do not seem to be called when this exception is thrown. In the following code, for std::vector for CFoo, only the time "~ CFoo" is displayed when temporary files in GetFooVect are destroyed and when rValue is copied to fooVect. The contents of fooVect are NOT destroyed.

This is my worst nightmare. I use RAII quite heavily. I lean quite heavily on my destructors for proper cleaning.

 class CFoo { public: ~CFoo() {printf(__FUNCTION__ "\n");} }; std::vector< CFoo > GetFooVect() { std::vector< CFoo > rValue; rValue.push_back(CFoo()); rValue.push_back(CFoo()); rValue.push_back(CFoo()); return rValue; } VOID CALLBACK Timer(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) { // My destructors aren't called? std::vector< CFoo> fooVect = GetFooVect(); // I'm destroyed CFoo aFoo; throw FooExcept(); printf("Also Here\n"); } 

I tried to recreate this by simply throwing / catching C ++ exceptions (i.e. removing the win32 timer callback variable) and the CFoo vector destroys just fine. For some reason, destructors DO NOT call here for things in vectors. What gives? Is there a logical explanation for this, or is it just weird, or both?

0
source share
1 answer

You should never allow an exception to propagate across the border of an API API (for example, a SetTimer callback). C (and the Windows API functions) know nothing about C ++ exceptions. You cannot rely on such code to propagate your exceptions.

The callback should catch all C ++ language exceptions before returning and handle the exceptions accordingly. If you need to somehow report exceptions to the rest of your application, you need to do it yourself.

(Someone here may be able to explain in detail what happens in this case, but the short answer is that you cannot rely on C code to do the right thing in the presence of a C ++ language exception, because it doesn't knows what a C ++ language exception is.)

+6
source

All Articles