记录以下boost::shared_ptr的一个使用细节

shared_ptr<T>::operator->返回的是T*类型指针,非const T*指针。因此通过const shared_ptr<T>&类型的ptr可以直接调用T各个原始的方法,不用担心const与非const问题。具体shared_ptr::operator->实现如下,摘自boost1.52.0版本boost\smart_ptr\shared_ptr.hpp

T * operator-> () const // never throws
{
      BOOST_ASSERT(px != 0);
      return px;
}

可以看出shared_ptr<T>的operator->中的const修饰,是指shared_ptr<T>对象自身,而非shared_ptr所管理的对象。

这个和普通原声指针还是有很大区别的,需要注意。

陈硕(@bnu_chenshuo)大牛对此有解释:const T*对应的是shared_ptr〈const T〉,const shared_ptr〈T〉对应的是T* const。注意二者之间的差别。

因此下面的代码是可以正确编译运行的

#include <boost/shared_ptr.hpp>
#include <iostream>

using namespace std;

class Item
{
public:
    Item(){}
    ~Item(){}
    
    void set(int data) { data_ = data; }
    
    void print(void)
    {
        cout<<"Item::data_: "<<data_<<endl;
    }
    
private:
    int data_;
};

typedef boost::shared_ptr<Item> ItemPtr;

void foo(const ItemPtr& item)
{
    item->set(3); // 此处item对应于Item* const类型
}

int main ()
{
    ItemPtr item(new Item);  // 此处item对应于Item* 类型
    foo(item);
    item->print();

    return 0;
}

  

posted @ 2014-07-07 14:39  lanyuliuyun  阅读(1079)  评论(0编辑  收藏  举报