Boost logo

Boost Users :

Subject: Re: [Boost-users] revisiting casting a boost::shared_ptr to void*
From: Leon Mlakar (leon_at_[hidden])
Date: 2014-07-29 02:55:42


On 29/07/14 06:46, Edward Diener wrote:
> 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*/boost-list/QE_VCTen1YQ/styxqKB2wbQJ
>>
>>
>> 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.
>
I concur. If the life time of the object needs to outlast the life time
of the last shared pointer pointing to it the use of shared pointers is
rather pointless. Otherwise it is safe to use get() and to pass the
returned raw pointer.

Regards,

Leon


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net