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*?
Just cast pointers to shared 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 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.)