Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost shared_ptr casting to void*

I'm using libev which requires casting my data to a void* to be in compliance with their predefined structs. I need to cast boost::shared_ptr to a void* and then cast the void* back to a boost::shared_ptr. Here is my code to do that

void foo(boost::shared_ptr<string>& a_string)
{
 void* data = (void*)a_string.get();
 boost::shared_ptr<string> myString((string*)data);
}

I'm pretty sure this works fine, however the way my code is setup I believe all shared_ptr references to my string are going out of scope as this casting method does not increase the use_count and thus shared_ptr is freeing the memory while I still need it.

Is there a way to manually increment/decrement the use_count? Ideally I would increment the use_count when I cast to a void*, pass my void* to another function, cast the void* back to a shared_ptr and decrement the use_count.

Or if anyone knows another solution to this problem I could use any help.

like image 961
Josh Brittain Avatar asked Mar 29 '12 03:03

Josh Brittain


1 Answers

The only real way to do this to allocate a shared_ptr somewhere that will live for long enough, and then set the void* to point to that.

like image 102
Puppy Avatar answered Sep 29 '22 23:09

Puppy