I have written below program to count the number of static and dynamically created object of the class.
#include <iostream>
class Test
{
public:
Test()
{
stackCount++;
}
void* operator new(size_t objSize)
{
void* ptr = malloc(objSize);
heapCount++;
return ptr;
}
static void Display()
{
std::cout << "stack object count : " << stackCount - heapCount << ", Heap object Count :" <<
heapCount << std::endl;
}
private:
static int stackCount;
static int heapCount;
};
int Test::stackCount = 0;
int Test::heapCount = 0;
int main()
{
Test obj1;
Test obj2;
Test obj3;
Test *ptr = new Test();
Test::Display();
return 0;
}
Program output : stack object count : 3, Heap object Count :1
is there any better way to maintain the count of static and dynamic object.?
new
, you allocate the memory for the object… but never call the object’s constructor. If you did that, you would see your counts don’t work. Why do you want to count heap versus “stack” objects anyway? What’s the point? \$\endgroup\$