Boost logo

Boost :

From: Bronek Kozicki (brok_at_[hidden])
Date: 2003-12-29 15:00:48

Jonathan Turkanis <technews_at_[hidden]> wrote:
> This question is addressed directly in the FAQ? (Q. Why doesn't
> shared_ptr provide a release() function? )

lets see FAQ answer:

: A. shared_ptr cannot give away ownership unless it's unique() because
: the other copy will still destroy the object

comment 1. in my real code pointer is always unique, at the point where
I want to initialize auto_ptr from it. Thus (assuming release is added)
it may contain:
 if (!unique())
   throw some_exception();

... and it's OK for me. Of course it means (in context of my previous
sample code) that following:

M m;
// ...
std::auto_ptr<int> p = m.source();

... will throw, but:

M m;
// ...
std::auto_ptr<int> p = m.source();

... will work, and this is what I actually need.

comment 2. if shared counter is reset to 0, there's no risk that any
copy of said shared pointer (assuming its non-unique) will try to delete
owned object. There is another risk though: at some point it may own bad
pointer. Overall I think that solution proposed in comment 1. is better.

: Furthermore, the pointer returned by release() would be difficult
: to deallocate reliably, as the source shared_ptr could have been
: created with a custom deleter.

I do not use deleters. And if I do, I would not ask for release. Now I
see that possibly I can simulate "release" with my own deleter (which
will delete or not pointed object, depending on some flag) + get +
reset. This will give me behaviour similar to 2. above. I would really
avoid it, as it makes whole project more complicated (I would need to
manage lifetime of deleters) and error prone.


Boost list run by bdawes at, gregod at, cpdaniel at, john at