Boost logo

Boost :

From: AlisdairM (alisdair.meredith_at_[hidden])
Date: 2003-12-11 04:39:09


The shared_ptr library is far more flexible than I realised. I've been
discovering new tricks all week and thought I would share the latest.

Conventional wisdom says a base class should either have a public virtual
destructor, if intended for use polymorphically, or a protected non-
virtual destructor if derivation is purely to inherit the implementation.

With shared_ptr, we can use this second type of class polymorphically as
well!

[see example below]

Not sure this is actually useful though, as I'm sure the shared_ptr
overhead is more than the cost of adding a virtual destructor ;¬ )

AlisdairM

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

namespace {

struct Deleter
{
template< class T >
void operator()( T *pt )
{
  delete pt;
}

};

struct dog
{
virtual void bark()
{
  std::cout << "woof!" << std::endl;
}

protected:
~dog()
{
  std::cout << "dog dies" << std::endl;
}

};

struct chihuahua : public dog
{
void bark()
{
  std::cout << "yap!" << std::endl;
}

~chihuahua()
{
  std::cout << "chihuahua dies" << std::endl;
}

};

int main()
{
  {boost::shared_ptr< dog > pet( new chihuahua, Deleter() );
  pet->bark();}
  return 0;
}


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