Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to count instances of an object

Tags:

I would like to know the exact number of instances of certain objects allocated at certain point of execution. Mostly for hunting possible memory leaks(I mostly use RAII, almost no new, but still I could forget .clear() on vector before adding new elements or something similar). Ofc I could have an

atomic<int> cntMyObject;

that I -- in destructor, ++ increase in constructor, cpy constructor(I hope I covered everything :)). But that is hardcoding for every class. And it is not simple do disable it in "Release" mode. So is there any simple elegant way that can be easily disabled to count object instances?

like image 885
NoSenseEtAl Avatar asked Aug 17 '11 18:08

NoSenseEtAl


People also ask

How do I count the number of instances of a class in C++?

If you use the CountObj, and make it the base class of the classes whose object you want to keep track of then, within the context of the thread in which the object was instantiated, the count will be incremented.

How do I count the number of instances in Python?

The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.


1 Answers

Have a "counted object" class that does the proper reference counting in its constructor(s) and destructor, then derive your objects that you want to track from it. You can then use the curiously recurring template pattern to get distinct counts for any object types you wish to track.

// warning: pseudo code

template <class Obj>
class CountedObj
{
public:
   CountedObj() {++total_;}
   CountedObj(const CountedObj& obj) {if(this != &obj) ++total_;}
   ~CountedObj() {--total_;}

   static size_t OustandingObjects() {return total_;}

private:
   static size_t total_;
};

class MyClass : private CountedObj<MyClass>
{};
like image 175
Chad Avatar answered Nov 27 '22 23:11

Chad