Boost logo

Boost :

Subject: [boost] [shared_ptr] delete shared_ptr
From: pavel novikov (paul.cpprules_at_[hidden])
Date: 2011-03-16 15:23:08


i'm excited to present you a technique which i occasionally invented
shared pointers are very good helpers
they help us to manage dynamically allocated memory
however it seems so natural i have never seen so far that one be
allowed to delete shared pointer
like this:

  shared_ptr<int>
    p = new int,
    q = p;
  delete p;
  assert(!p); //neither assertion fires
  assert(q);

in fact the technique is rather trivial
provide a distinct class like this:

  template<typename type>
  struct deleter : shared_ptr_base<type>
  {
    void operator delete(void *p)
    { reinterpret_cast<ptr_base*>(p)->detach(); }
  };

and let the 'operator unspecified_type_convertible_to_bool()' return
statically casted address of the ptr instance itself (or NULL) like
this:

  template<typename type> inline
  shared_ptr<type>::operator const deleter<type>*() const
  {
    if (!data)
      return 0;
    const shared_ptr_base<type> *base = this;
    return static_cast<const safe_deleter<type>*>(base); //oops! a little hack...
  }

minimum changes are needed to the existing library sources
this way the example above works perfectly

codepad.org is down so i just attached a toy programm with an
implementation of this technique (works at least in msvc10)

-- 
Pavel
P.S.
if you notice a grammar mistake or weird phrasing in my message
please point it out



Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk