Boost logo

Boost Users :

Subject: Re: [Boost-users] revisiting casting a boost::shared_ptr to void*
From: Dominique Devienne (ddevienne_at_[hidden])
Date: 2014-07-29 11:44:01


On Tue, Jul 29, 2014 at 4:49 PM, Chris Cleeland <chris.cleeland_at_[hidden]>
wrote:

> 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 will have to disagree with your assessment that using a shared pointer
> makes no sense. In my particular situation, the shared pointer is used in a
> C++ application, and it's a poster child for shared pointers. This
> mismatch occurs in a couple of places where I have to call into a C API and
> register a callback, providing a "context" or "cookie" or "Asynchronous
> Completion Token" to the registration. That context gets held in some
> container owned by the C API innards and, when the C API invokes the
> callback, it passes that context as an argument to the callback function.
>
> Ideally, the context would be the pointer to the same object held by the
> shared pointer--because that is the exact context I need in order to take
> action within the callback function.
>

You just new (heap alloc) a shared_ptr (as a copy of your existing
shared_ptr), and pass its address as the "user-data" as a void*, which the
callback casts back into the shared_ptr*, and deletes that one (makes it go
"out of scope", and if it's the last one, takes the pointed-object with him
to the grave). The heap-allocated shared_ptr gives you the ref-count bump
you need to keep the object alive. If your C API does not "leak", calls the
callback appropriately, you don't leak anything.

I used the technique with SQLite. --DD



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