views:

228

answers:

2

Hey guys another quick question here that got me thinking.

In generating windows dll dynamic libraries, you are asked declare which functions should be exported so that some functions maybe left private to the dll and not accessible by other applications.

I haven't seen anything mentioned regarding whether destructors need to be exported or are they automatically handled by the compiler or windows kernel? As in if I don't export the destructor and they dynamically allocate a class which I declared to be exportable, can they successfully call delete on it if the destructor is not exported?

Any help on this is welcome and appreciated.

+1  A: 

The compiler should generate an error if the destructor isn't available but needs to be. As a general rule, if your constructor is exported, your destructor should be too.

Mark Ransom
+3  A: 

In general, any class with a constructor should export the destructor as well.

That being said, there are a couple of things to be wary of here...

If you're building on Windows, you need to be careful about mixing VS versions with libraries. If you're only going to be distributing your library as a DLL, exporting constructors and destructors is a bad idea. The problem is in the C++ runtimes. It's pretty much a requirement that the same runtime that handles memory allocation needs to handle the deallocation. This is the #1 cause of "bad things" that happen when you try to use a library compiled in VS 2005 from within VS 2008, for example.

The solution for this is to provide factory methods to create your class (allocation is handled by the runtime with which you compiled) as well as methods to delete/destruct your class (so the deallocation happens in the same runtime).

Reed Copsey
Going the factory-function route also opens the possibility of the DLL being consumed by non-C++ programs, which I hope everyone considers to be a good thing.
Rob Kennedy
Okay so generally it can be a bad thing to export destructors. I was actually planning on using factor methods for creation so I might go ahead with that. Also for clarity, could you guys explain a bit more on why it is such a bad thing that the same runtime de-allocates and allocates?
iQ
@IQ: If the VC2005 runtime deletes something that was allocated by VC2008's runtime, you can get (occasional, and very difficult to track) bugs that cause things like memory corruption, crashes, etc. Keeping the runtimes consistent prevents that.
Reed Copsey