A common way of accomplishing this is with a class template from which you inherit.
template <typename T>
class Countable
{
static unsigned cs_count_;
public:
Countable() { ++cs_count_; }
Countable( Countable const& ) { ++cs_count_; }
virtual ~Countable() { --cs_count_; }
static unsigned count() { return cs_count_; }
};
template <typename T>
unsigned Countable<T>::cs_count_ = 0;
So to use this I would write:
class MyClass : public Countable<MyClass> { };
Below is a thread-safe version. It uses a class from boost to ensure the increment, decrement, and read operations are atomic on the supported platforms.
#include <boost/detail/atomic_count.hpp>
template <typename T>
class Countable
{
static boost::detail::atomic_count cs_count_;
protected:
~Countable() { --cs_count_; }
public:
Countable() { ++cs_count_; }
Countable( Countable const& ) { ++cs_count_; }
static unsigned count() { return cs_count_; }
};
template <typename T>
boost::detail::atomic_count Countable<T>::cs_count_(0);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…