【发布时间】:2011-05-07 21:17:00
【问题描述】:
有人会怎么做? 例如:
Client* client = it->second;
it->second 是对客户端的 boost::shared_ptr 错误:
cannot convert `const ClientPtr' to `Client*' in initialization
【问题讨论】:
标签: c++ boost boost-smart-ptr
有人会怎么做? 例如:
Client* client = it->second;
it->second 是对客户端的 boost::shared_ptr 错误:
cannot convert `const ClientPtr' to `Client*' in initialization
【问题讨论】:
标签: c++ boost boost-smart-ptr
boost::shared_ptr 有一个 .get() 方法来检索原始指针。
关于何时以及为什么不使用它的文档:http://www.boost.org/doc/libs/1_44_0/libs/smart_ptr/shared_ptr.htm
【讨论】:
您可以使用boost::shared_ptr 上的get 方法来检索指针,但要非常小心操作:从引用计数的共享指针中提取裸指针可能很危险(如果引用计数达到零,将触发删除,从而使您的原始指针无效)。
【讨论】:
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的指针),不适用于其他类型的指针。
【讨论】:
operator&() 可能会过载,所以我会坚持使用.get()
不危险,但涉及 c-ctor。
Client client( *(it->second.get()) );
【讨论】: