Is it safe to use STL (TR1) shared_ptr's between modules (exes and dlls)

后端 未结 5 1588
借酒劲吻你
借酒劲吻你 2020-12-28 19:14

I know that new-ing something in one module and delete-ing it in another can often cause problems in VC++. Problems with different runtimes. Mixing modules with staticly lin

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 19:47

    Freeing the memory is safe, so long as it all came from the same memory management context. You've identified the most common issue (different C++ runtimes); having separate heaps is another less-common issue you can run into.

    Another issue which you didn't mention, but which can be exascerbated by shared pointers, is when an object's code exists in the DLL and is created by the DLL, but another object outside the DLL ends up with a reference to it (via shared pointer). If that object is destroyed after the DLL is unloaded (for example, if it's a module-level static, or if the DLL is explicitly unloaded by FreeLibrary(), the shared object's destructor will crash.

    This can bite you if you attempt to write DLL-based, loosely-coupled plugins. It's also the reason that COM lets DLLs decide when they can be unloaded, rather than letting COM servers demand-unload them.

提交回复
热议问题