Boost shared_ptr casting to void *

I use libev, which requires pouring my data into void * so that it matches their predefined structures. I need to enable boost :: shared_ptr in void * and then return void * back to boost :: shared_ptr. Here is my code to do this

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

I'm sure this works fine, however, as my code is configured, I believe that all shared_ptr links to my string are out of scope, since this casting method does not increase the value of use_count, and therefore shared_ptr frees up memory while I still need this one.

Is there a way to manually increase / decrease the value of the use_count parameter? Ideally, I would increase the value of use_count when I applied void *, pass my void * to another function, return void * back to shared_ptr and decrease the value of use_count.

Or, if someone knows another solution to this problem, I can use any help.

+5
source share
3 answers

The only real way to do this is to highlight shared_ptrsomewhere that will live long enough and then install void*to point it out.

+4
source

If you return void*back to boost::shared_ptr, it will be a new generic pointer, unrelated to other other pointers, which also point to the memory the variable points to `void*.

I think you need to add enabled_shared_from_thissupport for the classes that you are going to use with shared_ptrs with this code.

shared_ptr, shared_ptrs - (shared_from_this) .

. boost enabled_shared_from_this docs.

+1

weak_ptr:

shared_ptr<int> p(new int(5));
weak_ptr<int> q(p);

: , ; , .

: , , a_string shared_ptr (, refrount β†’ release),

:

void foo(boost::shared_ptr<string>& a_string)
{
 void* data = (void*)a_string.get();
 boost::shared_ptr<string> myString((string*)data);
 weak_ptr<string> temp(a_string); // prevent destruction before above line
 // or reference a_string in any meaningless way that CANT be optimised out 
 // pre-emptively by the compiler
}

a_string - - foo , void ( void)

0
source

All Articles