Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c++ - How can I safely (and easily) count *all* instances of a class within my program?

I would like to be able to instantiate a particular (and otherwise normal) class (the source of which I can modify) and count the number of times the class has been instantiated (e.g. like this). But I would like to include all instances in my total count, even some which are created via the copy constructor in standard containers.

Would it be appropriate to have all the constructors (including the copy constructor) of my class increment a static counter? If so, is it possible to ensure my class still conforms to the requirements of standard containers (i.e., T(x) is equivalent to x), by overriding other operators for example?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...