Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should destructors be exported in Windows DLL Libraries?

In generating Windows DLL dynamic libraries, you are asked to 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?

like image 540
iQ. Avatar asked Dec 28 '25 22:12

iQ.


2 Answers

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).

like image 178
Reed Copsey Avatar answered Dec 31 '25 12:12

Reed Copsey


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.

like image 21
Mark Ransom Avatar answered Dec 31 '25 11:12

Mark Ransom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!