开发者

Convert boost::shared_ptr to actual class

How would someone do that? for example:

Client* client = it->second;

where it->second is a boost::shared_ptr to Client error:

cannot convert `const Cli开发者_如何转开发entPtr' to `Client*' in initialization


boost::shared_ptr has a .get() method to retrieve the raw pointer.

Documentation here about when and why not to use it: http://www.boost.org/doc/libs/1_44_0/libs/smart_ptr/shared_ptr.htm


You can use the get method on the boost::shared_ptr to retrieve the pointer, but be very careful in what you do : extracting a naked pointer from a reference counted shared pointer can be dangerous (deletion will be triggered if the reference count reaches zero, thus invalidating your raw pointer).


boost:shared_ptr overloads operator*:

boost::shared_ptr< T > t_ptr(new T());
*t_ptr; // this expression is a T object

To get a pointer to t you can either use get function or take *t_ptr address:

&*t_ptr; // this expression is a T*

The first method (using get) is probably better, and has less overhead, but it only works with shared_ptrs (or pointers with a compatible API), not with other kind of pointers.


Not dangerous but c-ctor involved.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜