const与智能指针:const shared_ptr<T>&

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

?
1
2
3
4
5
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。注意二者之间的差别。

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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;
}

  

转载自:[记录以下boost::shared_ptr的一个使用细节](https://www.cnblogs.com/lanyuliuyun/p/3829664.html)

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值