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(); }