Destructor is not called when an exception is propagating from unmanaged to mixed code.

C

caa

I have made a simple text example. I have two projects. First is an
unmanaged static lib, containing function F(), which created an object
of type A and throws an exception. The second project is a C++/ME
console application that calls F() and catches all exceptions with a
"catch(...)" filter. The thing that I dont understand is why doesn't
the auto object created on stack get destroyed. See my sources:

Project 1. Unmanaged lib.
================================= Lib.cpp
#include "Lib.h"
#include <stdio.h>
#include <stdexcept>

namespace ns
{
class A
{
public:
A()
{
}

~A()
{
FILE * f = fopen( "c:/Temp/info.txt", "w+" );
fprintf( f, "destructor called!" );
fclose( f );
}
};

void F()
{
A a;
throw std::domain_error( "Ahhh hell..." );
}
}

Project 2. Managed console app.
================================ consoleApp.cpp
#include "stdafx.h"
#include "../../VS2005_Unmanaged_Lib/VS2005_Unmanaged_Lib/Lib.h"

int main()
{
try
{
ns::F();
}
catch (...)
{
System::Console::WriteLine( S"Caught it" );
}
}

When I run the console app I dont see no files beeing created. SO I
guess the destructor doesn't get called. Well... why? Just in case, I
m compiling with VS2005.
 
B

Ben Voigt [C++ MVP]

I have made a simple text example. I have two projects. First is an
unmanaged static lib, containing function F(), which created an object
of type A and throws an exception. The second project is a C++/ME
console application that calls F() and catches all exceptions with a
"catch(...)" filter. The thing that I dont understand is why doesn't
the auto object created on stack get destroyed. See my sources:

What /EH option was the static library compiled with? /EHa is pretty much
required in a managed program.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top