On 7/28/2014 11:22 PM, Chris Cleeland wrote:
I'm resurrecting this topic:
https://groups.google.com/forum/#!searchin/boost-list/shared_ptr$20void*/boo...
because there is an unaddressed issue in it that I'm about to run into:
"... beware the pointee may be deleted if the last copy of the shared pointer goes out of scope, as the raw pointer won't have incremented the reference count."
I cannot be the first person to run into this--a common issue when crossing an API boundary. Has anyone come up with a good, safe solution wherein the reference count gets properly incremented?
The issue has nothing to do with casting a shared pointer to a void *. If you need to pass a shared pointer as any raw pointer, if the last use of the shared pointer ends the encapsulated raw pointer is deleted. If someone is still holding on to that raw pointer after that happens and tries to use it you will almost cetainly get a crash. There is no good solution to this other than not using a shared pointer in the first place in your particular situation. Think about your problem. You want to be able to share this pointer among other objects but then you want one or more objects to share this pointer as a raw pointer. Given what a shared pointer is, doing this just does not make sense. If you are just passing your shared pointer to a function as a raw T * you have no problem if the function is a synchronous function which does not hold on to the raw pointer past the functions exit. This is because the shared pointer from which the raw pointer is passed will still be in scope when your function returns.