【问题标题】:Convert boost::shared_ptr to actual class将 boost::shared_ptr 转换为实际类
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        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&amp;() 可能会过载,所以我会坚持使用.get()
        【解决方案4】:

        不危险,但涉及 c-ctor。

        Client client( *(it->second.get()) );
        

        【讨论】:

          猜你喜欢
          • 2011-04-22
          • 1970-01-01
          • 1970-01-01
          • 2017-10-08
          • 1970-01-01
          • 2011-09-13
          • 1970-01-01
          • 1970-01-01
          • 2020-04-06
          相关资源
          最近更新 更多