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)