Boost logo

Boost Users :

Subject: Re: [Boost-users] revisiting casting a boost::shared_ptr to void*
From: Richard Damon (Richard_at_[hidden])
Date: 2014-07-29 22:34:09


On 7/29/14, 10:15 PM, Gavin Lambert wrote:
> On 30/07/2014 14:01, Michael Powell wrote:
>> Not to beat a dead horse. But here's an apt analogy: I could be wrong,
>> but you are dividing by zero and not expecting a div by zero exception
>> (or worse) to occur.
>
> I don't see how that's even slightly a valid analogy.
>
>
> In any case, what the OP needs to do is to characterise the lifetime
> of the raw pointer as used by the C API, and *absolutely guarantee*
> that some shared_ptr exists at least as long as that.
>
> There are various techniques for doing this, depending on what that
> lifetime is -- for example, if it's a single-shot callback then
> Dominique's suggestion might be reasonable, if you don't mind paying
> an extra allocation/deallocation each cycle. If it's a multi-shot
> callback then it may be better to make a connection-management object
> that registers/unregisters with the C API and then manage the
> lifecycle of *that* object appropriately. There's many methods.
>
> But you have to know what the C API is going to be doing with that
> pointer, or all bets are off.
>
Another way of looking at it is that a C program that gives this API a
pointer, needs to make sure that the pointer remains valid until the
library is done with it. In C++ this doesn't change.

The difference is that in C, if this is a heap allocation, you need to
explicitly decide to destroy the block, while in C++, if it has been put
under control of a shared_ptr, it may automatically go away based on the
rules of shared_ptr. Thus the program needs to let shared_ptr know that
the block is still in use, and one simple way of doing this is to make a
shared_ptr that will exist as long as you need the block to continue.

This happens anytime a pointer to an object under the control of
shared_ptr move outside the control of shared_ptr.

-- 
Richard Damon

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