Re: Transfer functionality for shared_ptr
In article <qqmabqoaqc3.fsf@hafnium.numerica.us>,
dgsteffen@numerica.us (Dave Steffen) wrote:
Our use case is this: we have a chunk of code that stores shared
pointers in a queue. We now pop these shared pointers off the queue
in function A and pass them into a 3rd party library that offers a
very C-ish interface; we send in void*'s (argh). Later, in function
B, we get the void*'s back and can call delete on them.
It sounds like what you really want is unique_ptr when it is available.
The problem is that when we pop the shared pointers off the queue in
function A, they go out of scope at the end of the function call and
delete what they hold.
Now, we know for an absolute fact that in function A use_count() ==
1. We can, of course, copy the underlying information out and work
with that, but that seems wasteful. We'd like to get a pointer to
the data out of the shared pointer and relieve the shared pointer of
the responsibility for cleaning it up.
Another possibility is, when you take them off the queue, store them in
a set<shared_ptr<T> > (or maybe a map<T*, shared_ptr<T> >, if you have
to do lookup by raw pointer). Instead of calling delete on them when
you are done, call s.erase(p). The advantage to this is that you can
still have a custom deleter. The disadvantage is that it is O(log N),
not O(1).
The solution we're pursuing right now is to change what we store in
the queue (e.g. don't store smart pointers). Arguably we shouldn't
be using them anyway, in this case, but going back to raw pointers
instead really goes against the grain. :-)
Still another choice is to use a Boost Pointer Container
<http://www.boost.org/libs/ptr_container/doc/ptr_container.html>, which
has the advantage of less overhead than shared_ptr.
Regards
--
Nevin ":-)" Liber <mailto:nevin@eviloverlord.com> 773 961-1620
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]