Throwing C++ exceptions across DLL boundaries

前端 未结 2 1790
庸人自扰
庸人自扰 2020-12-05 13:35

I\'ve read various things about how one should not allocate heap memory in one DLL and deallocate it from outside that DLL. But what about throwing an exception object that

相关标签:
2条回答
  • 2020-12-05 13:56

    Throwing C++ exceptions across DLL boundaries is only possible when all modules use the same C++ runtime, in which case they share a heap as well. But this can be a maintenance burden, especially when libraries from multiple vendors are involved, so it is discouraged.

    If you want error-handling which is portable across multiple compilers/compiler versions/compiler settings, either use return codes or OS-provided exceptions (e.g. SEH on Windows)/

    0 讨论(0)
  • 2020-12-05 14:04

    It depends how that memory was allocated and whether the mechanism to do so ("the runtime" or "memory manager") is shared between the specific DLL and the other parts of the application. E.g. a throw new my_exception( args ); could also be in order depending on the details.

    You could make your exception reference counted, so that it comes with the intrinsic knowledge of how to destroy its own instance (and owned memory).

    Using IMalloc (see MSDN) for instance allocation and placement new would be another way (call OleInitialize before) ...

    Indeed, the memory allocation is an issue depending on what is being used. For example mixing statically linked CRT and dynamically linked CRT in different parts of an application will lead to issues the same way the mixing debug and release code would. The problem here is that the code that is supposed to free the memory uses a different "memory manager". But if the thrown object knows about its own destruction, it should be fine, since the dtor code would reside in the same compilation unit as the one allocating it.

    0 讨论(0)
提交回复
热议问题