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;
}```