Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn boost::shared_ptr<> into a reference (&)?

So I have a class that uses references (&) with functions like

void request(tcp::socket& socket); 

I am starting migrating all my code to boost::shared_ptr<tcp::socket> but I would really like to know how to turn my shared_ptrs into references so to be capable to make my code evolve function by function and not in one iteration changing all I have into shared_ptr. So how to turn a shared_ptr into a reference?

like image 832
Rella Avatar asked Apr 14 '11 05:04

Rella


2 Answers

First, they're not called links, but references. :)
Second, the boost::shared_ptr can just be dereferenced like normal pointer:

boost::shared_ptr<tcp::socket> p(new tcp::socket());
// can be done in two steps (dereference, pass)
tcp::socket& socket_ref = *p;
request(socket_ref);
// or one step
request(*p);
//      ^ -- dereference the shared_ptr
like image 67
Xeo Avatar answered Sep 21 '22 21:09

Xeo


boost::shared_ptr<tcp::socket> sock;

...

if (sock) request( *sock )

I think it's better to rewrite request() (if you can) so that it can handle boost::shared_ptr or general pointers.

like image 23
maverik Avatar answered Sep 20 '22 21:09

maverik