Search code examples
c++boostcastingshared-ptrvoid-pointers

How can i cast between void* and boost shared ptr


I've got these lines:

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

and i want to be able to do something like this:

A_SPtr instance = (void*)(var);

how can i do it? Also, how can i cast the other way around meaning from the shared_ptr to void*?


Solution

  • Just cast pointers to shared pointers to and from void *.

    1. shared_ptr to void *:

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

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

    CAUTION: This passes a pointer to the shared pointer to the thread. This will not work if the shared pointer does not remain in existence through the life of the thread function – otherwise, the thread will have a pointer to an object (the shared pointer) that no longer exists. If you cannot meet that requirement, pass a pointer to a new shared_ptr and delete it when the thread is done with it. (Or use boost:bind which works with shared pointers directly.)