在模块(exe和dll)之间使用STL(TR1)shared_ptr是否安全? [英] Is it safe to use STL (TR1) shared_ptr's between modules (exes and dlls)

查看:137
本文介绍了在模块(exe和dll)之间使用STL(TR1)shared_ptr是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在一个模块中添加某些内容并在另一个模块中删除它通常会在VC ++中引起问题.不同运行时的问题.如果我没记错的话,混合使用静态链接的运行时模块和/或动态链接的版本控制不匹配的模块都可能搞砸.

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 linked runtimes and/or dynamically linked versioning mismatches both can screw stuff up if I recall correctly.

但是,跨模块使用VC ++ 2008的std :: tr1 :: shared_ptr是否安全?

由于只有一个版本的运行时甚至不知道什么是shared_ptr,因此静态链接是我唯一的危险(目前为止).我以为我已经读过boost这样的shared_ptr版本是可以安全使用的,但是我使用的是Redmond版本...

Since there is only one version of the runtime that even knows what what a shared_ptr is, static linking is my only danger (for now...). I thought I've read that boost's version of a shared_ptr was safe to use like this, but I'm using Redmond's version...

我正在尝试避免对分配模块中的空闲对象进行特殊调用. (或类本身中的删除此内容"之类的内容).如果这一切看起来有些怪异,那么我正在使用它进行单元测试.如果您曾经尝试对现有C ++代码进行单元测试,则可以了解有时需要 creative 的方式.我的内存是由EXE分配的,但最终会在DLL中释放(如果引用计数按我认为的方式起作用).

I'm trying to avoid having a special call to free objects in the allocating module. (or something like a "delete this" in the class itself). If this all seems a little hacky, I'm using this for unit testing. If you've ever tried to unit test existing C++ code you can understand how creative you need to be at times. My memory is allocated by an EXE, but ultimately will be freed in a DLL (if the reference counting works the way I think it does).

推荐答案

释放内存是安全的,只要所有内存来自相同的内存管理上下文即可.您已经确定了最常见的问题(不同的C ++运行时);具有单独的堆是您可能遇到的另一个较不常见的问题.

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.

您没有提到的另一个问题,但是可以通过共享指针来解决,当对象的代码存在于DLL中并由DLL创建时,但是DLL之外的另一个对象最终以对其进行引用而结束(通过共享指针).如果该对象在DLL卸载后被销毁(例如,如果它是模块级静态对象,或者如果FreeLibrary()显式卸载了DLL,则共享对象的析构函数将崩溃.

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.

如果尝试编写基于DLL的松耦合插件,这可能会给您带来麻烦.这也是COM让DLL决定何时可以卸载它们 的原因,而不是让COM服务器按需卸载它们的原因.

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.

这篇关于在模块(exe和dll)之间使用STL(TR1)shared_ptr是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆