2

有人会怎么做?例如:

Client* client = it->second;

其中 it->second 是 boost::shared_ptr 到客户端错误:

cannot convert `const ClientPtr' to `Client*' in initialization
4

4 回答 4

7

boost::shared_ptr 有一个 .get() 方法来检索原始指针。

关于何时以及为什么不使用它的文档:http: //www.boost.org/doc/libs/1_44_0/libs/smart_ptr/shared_ptr.htm

于 2010-11-10T13:18:01.167 回答
7

您可以使用 上的get方法boost::shared_ptr来检索指针,但要非常小心:从引用计数的共享指针中提取裸指针可能很危险(如果引用计数达到零,将触发删除,从而使您的原始指针)。

于 2010-11-10T13:18:47.790 回答
2

boost:shared_ptr重载operator*

boost::shared_ptr< T > t_ptr(new T());
*t_ptr; // this expression is a T object

要获得指向t您的指针,可以使用get函数或获取*t_ptr地址:

&*t_ptr; // this expression is a T*

第一种方法(使用get)可能更好,并且开销更少,但它仅适用于shared_ptrs (或具有兼容 API 的指针),不适用于其他类型的指针。

于 2010-11-10T13:19:49.887 回答
1

不危险,但涉及 c-ctor。

Client client( *(it->second.get()) );
于 2010-11-10T14:47:09.993 回答