Boost logo

Boost Users :

Subject: Re: [Boost-users] [shared_ptr] deleter that destroys shared_ptr - is it safe?
From: Stefan Strasser (strasser_at_[hidden])
Date: 2009-09-08 21:34:10


Am Tuesday 08 September 2009 23:28:21 schrieb Igor R:
> Hello,
>
> Is the following code legal and safe -
> a) according to the shared_ptr specs
> b) with the current boost::shared_ptr implementation
>

it is, because shared_ptr::reset() is specified to be equivalent to
shared_ptr().swap(*this).
so the contents of a::p_ are first swap()ed to a temporary and then p is
deleted when the temporary goes out of scope, with a::p_ being empty.

however, be careful that you leave it at reset() and don't change it to an
assignment.
p_=shared_ptr<a>(); is NOT safe and is not equivalent to p_.reset() in this
case.
the assignment in fact produces a invalid write with the current
implementation.

> Thanks!
>
>
> struct a
> {
> a() : p_(this, mem_fn(&a::delete_me))
> {}
> void reset()
> {
> p_.reset();
> }
> void delete_me()
> {
> delete this;
> }
>
> shared_ptr<a> p_;
> };
>
>
> int main()
> {
> a* p = new a;
> p->reset();
> }


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