是否确定使用boost ::共享PTR在DLL接口? [英] Is it OK to use boost::shared ptr in DLL interface?

查看:129
本文介绍了是否确定使用boost ::共享PTR在DLL接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是不是有效开发C ++中的DLL返回升压共享指针,并用它们作为参数?

Is it valid to develop a DLL in C++ that returns boost shared pointers and uses them as parameters?

那么,是不是确定导出功能,这样吗?

So, is it ok to export functions like this?

1.) boost::shared_ptr<Connection> startConnection();
2.) void sendToConnection(boost::shared_ptr<Connection> conn, byte* data, int len);

在特殊:是否跨越边界的DLL引用计数的工作或将要求是EXE和DLL使用相同的运行时间

In special: Does the reference count work across DLL boundaries or would the requirement be that exe and dll use the same runtime?

的目的是克服与对象所有权的问题。因此,该对象被删除时,DLL和EXE不引用它了。

The intention is to overcome the problems with object ownership. So the object gets deleted when both dll and exe don't reference it any more.

推荐答案

据++斯科特迈尔斯有效C(第3版),shared_ptrs跨边界的DLL安全。 shared_ptr的对象会保持一个指针,从创建它的dll的析构函数。

According to Scott Meyers in Effective C++ (3rd Edition), shared_ptrs are safe across dll boundaries. The shared_ptr object keeps a pointer to the destructor from the dll that created it.

在他的18项他说,书的一个特别好的特性
  TR1 :: shared_ptr的是,它会自动使用它的每个指针的删除
  消除另一种潜在的客户错误,跨DLL问题。
  使用新创建一个对象时,这个问题作物起来
  动态链接库(DLL),但在一个不同的DLL将被删除。上
  许多平台上,这样的跨DLL新/删除对导致运行时
  错误。 TR1 :: shared_ptr的避免这个问题,因为它的默认删除器
  使用从其中创建TR1的:: shared_ptr的同一个DLL中删除。

In his book in Item 18 he states, "An especially nice feature of tr1::shared_ptr is that it automatically uses its per-pointer deleter to eliminate another potential client error, the "cross-DLL problem." This problem crops up when an object is created using new in one dynamically linked library (DLL) but is deleted in a different DLL. On many platforms, such cross-DLL new/delete pairs lead to runtime errors. tr1::shared_ptr avoid the problem, because its default deleter uses delete from the same DLL where the tr1::shared_ptr is created."

蒂姆·莱舍有一个有趣的疑难杂症,以观看,虽然,他提到<一个href=\"http://stackoverflow.com/questions/345003/is-it-safe-to-use-stl-tr1-shared-ptrs-between-modules-exes-and-dlls\">here.你需要确保之前的shared_ptr终于超出范围创建shared_ptr的DLL是不卸载。我要说的是,在大多数情况下,这是不是你看的东西,但如果你正在创建将被松耦合的dll我会建议不要使用一个shared_ptr。

Tim Lesher has an interesting gotcha to watch for, though, that he mentions here. You need to make sure that the DLL that created the shared_ptr isn't unloaded before the shared_ptr finally goes out of scope. I would say that in most cases this isn't something you have to watch for, but if you're creating dlls that will be loosely coupled then I would recommend against using a shared_ptr.

另一个潜在的不利因素是确保两面用Boost库的兼容版本创建的。 Boost的shared_ptr的已经稳定了很长一段时间。至少从 1.34 它已经TR1兼容。

Another potential downside is making sure both sides are created with compatible versions of the boost library. Boost's shared_ptr has been stable for a long while. At least since 1.34 it's been tr1 compatible.

这篇关于是否确定使用boost ::共享PTR在DLL接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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