微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在DLL接口中使用boost :: shared ptr可以吗?

在C中开发一个DLL可以返回升级共享指针并将其用作参数是否有效?

那么输出这样的功能可以吗?

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

特别的:引用计数是否跨DLL的边界工作,或者是exe和dll使用相同的运行时间?

目的是克服对象所有权问题.所以当dll和exe不再引用它时,对象被删除.

根据有效C(第3版)的Scott Meyers的说法,shared_ptrs在dll边界上是安全的. 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.”

Tim Lesher有一个有趣的呵呵,但是他提到了here.你需要确保在shared_ptr最终超出范围之前创建shared_ptr的DLL不会被卸载.我会说,在大多数情况下,这不是你必须注意的事情,但如果你正在创建一个松散耦合的dll,那么我建议不要使用shared_ptr.

一个潜在的缺点是确保双方都是使用兼容版本的boost库创建的. Boost的shared_ptr已经稳定了很久.至少从1.34起,它已经被tr1兼容了.

原文地址:https://www.jb51.cc/windows/364099.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐