When a C++ destructor did not run – Part 2

In the previous post, we saw that linking a C++ static library compiled with /EHs to a mixed mode application prevented the destructor from running when an exception is thrown. Here’s the sample project that demonstrates the behavior, in case you aren’t convinced. This is the code inside the library. 1: C::C() 2: { 3: cout << "Constructed" << endl; 4: } 5:  6: C::~C() 7: { 8: cout << "Destructed" << endl; 9: } 10:  11: void SomeFunc() 12: { 13: C c; 14: throw std::exception("Gone"); 15: } And this is the code consuming the library. 1: int main(array<System::String … Continue reading When a C++ destructor did not run – Part 2

When a C++ destructor did not run – Part 1

Consider this piece of C++ code. 1: using namespace std; 2:  3: class C 4: { 5: public: 6: C() 7: { 8: cout << “Constructed”; 9: } 10: ~C() 11: { 12: cout << “Destructed”; 13: } 14: }; 15:  16: void SomeFunc() 17: { 18: C c; 19: throw std::exception(“Gone”); 20: } If you know any C++ at all, you’ll know that when SomeFunc returns, both “Constructed” and “Destructed” will be printed to the console. That is because C++ guarantees that the destructor of an object created on the stack will always run when control leaves the scope, … Continue reading When a C++ destructor did not run – Part 1