From: Daniel Frey (d.frey_at_[hidden])
Date: 2007-11-04 03:00:50


On Sat, 2007-11-03 at 19:45 -0400, Mike Tegtmeyer wrote:
> I guess if shared_ptr was to be done all over again, I think that I
> would argue that it should act like a pointer, ie you shouldn't be
> able to 'delete' a 'null' pointer - whatever delete and null mean for

Let's keep shared_ptr like it is. What you (and others) probably need is
the right helper, as a quick hack it looks like this:

#include <iostream>
#include <boost/shared_ptr.hpp>

struct X {};

void freeX( X* x )
{
  // Should not be called with a null pointer
  std::cout << "free " << x << std::endl;
}

template< typename T >
struct on_nonzero_t
{
  typedef void (&F)( T* );
  F f_;

  on_nonzero_t( F f ) : f_( f ) {}
  void operator()( T* t ) const { if( t ) f_( t ); }
};

template< typename T >
on_nonzero_t< T > on_nonzero( void (&f)( T* ) )
{
  return on_nonzero_t< T >( f );
}

void f( X* x )
{
  std::cout << "x = " << x << std::endl;
  boost::shared_ptr< X > tmp( x, on_nonzero( freeX ) );
}

int main()
{
  X x;
  f( &x );

  f( 0 );
}

The naming of the helper might be crap, but anyway, hope you can make
some use of it...

Regards, Daniel