How can I throw between void * and boost shared ptr

I have the following lines:

typedef boost::shared_ptr<A> A_SPtr; void *f(void* var){ ... 

and I want to do something like this:

 A_SPtr instance = (void*)(var); 

How can i do this? Also, how can I distinguish another path from shared_ptr to void *?

+4
source share
2 answers

Just draw pointers to generic pointers to and from void * .

  • shared_ptr to void * :

     f (reinterpret_cast<void *>;(&A_SPtr)); 
  • void * back to shared_ptr :

     A_SPtr instance = * reinterpret_cast(boost::shared_ptr<A>*)(var); 

CAUTION: This passes a pointer to a generic stream pointer. This will not work if the common pointer does not exist during the life of the stream function - otherwise the stream will have a pointer to an object (shared pointer) that no longer exists. If you cannot fulfill this requirement, pass a pointer to the new shared_ptr and delete when the thread executes with it. (Or use boost:bind , which works with shared pointers directly.)

+6
source

As long as you are sure that all rights to use void* transferred to you in f, that void* really refers to object A , and you know the correct way to clear up, then you can just go ahead and use the smart pointer to accept the right ownership:

 typedef boost::shared_ptr<A> A_SPtr; void *f(void *var){ A_SPtr instance(static_cast<A*>(var)); } 

Edit: this is not clear from the question, but some comments show that you are actually trying to pass a smart pointer through the β€œcommon” interface that void* uses. You do this the same way as for any type:

 void *f(void *var){ A_SPtr *instance = static_cast<A_SPtr *>(var); } 

And you pass a pointer like:

 A_SPtr a; f(&a); 

Like any pointer, you must make sure that the lifetime of the object is sufficient for the pointer to be valid when f receives it.

0
source

All Articles