C++ Static objects in DLLs not having destructors called

浪子不回头ぞ 提交于 2019-12-06 08:03:47

This is my experience.

I bound my DLL explicitly by using LoadLibrary. When FreeLibrary called, some access violations has been occurred inside destructors. That unload the DLL immediately and following destructors called from (*function_to_call)(); in the DLL has been cancelled.

A weird thing is Visual Studio doesn't break when the access violation occurred. Then execution has continued from FreeLibrary as if the program done without errors. It looks everything OK except some static objects not having destructor called.

I found bugs with following settings. This changed Visual Studio's behaviour when access violation occurred inside destructors in my DLL.

Ctrl+Alt+E shows this dialog box. At that time I used Visual Studio 2010.

Static destructors are typically registered by the C++ runtime to run via the atexit() function. But they are registered only for applications, not DLLs. And the reason is that DLLs can be loaded and unloaded on the fly. If DLLs registered atexit functions, those function pointers would dangle when the DLL is unloaded and would cause a crash when the program actually exits.

Try to avoid static objects in DLLs. If you absolutely need to have them, then expose initialization and cleanup functions in the library so the user can deal with this. Then convert those variables to pointers and new them on init, delete them on deinit.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!