To find the no of objects created on Heap and Stack. To create the object on the heap we use new so override the new and delete keywords to keep track of the counter.
class Test
{
static int heapcount;
static int stackcount;
public:
static int GetHeapCount()
{
return heapcount;
}
static int GetStackCount()
{
//The objects which are created on heap also will call constructor and increment the stack count, so remove the objects that are created on heap to get stack count
return stackcount - heapcount;
}
Test()
{
++stackcount;
}
~Test()
{
--stackcount;
}
void* operator new(size_t size)
{
++heapcount;
void * p = malloc(sizeof(Test));
return p;
}
void operator delete(void* p)
{
--heapcount;
free(p);
}
void operator=(Test const& obj)
{
int x = 0;
}
};
int Test::heapcount = 0;
int Test::stackcount = 0;
int main()
{
{
Test t;
Test t2;
Test* t1 = new Test();
std::cout << "HeapCount = " << Test::GetHeapCount() << std::endl;//HeapCount = 1 (t1)
std::cout << "StackCount = " << Test::GetStackCount() << std::endl;//StackCount = 2 (t,t2)
delete t1;
}
//As all the objects are deleted so count must be zero, stack objects will be removed when goes out of scope
std::cout << "HeapCount = " << Test::GetHeapCount() << std::endl;//HeapCount = 0
std::cout << "StackCount = " << Test::GetStackCount() << std::endl;//StackCount=0
{
Test t[3];
Test* t2 = new Test();
Test* t3 = new Test();
std::cout << "HeapCount = " << Test::GetHeapCount() << std::endl;//HeapCount = 2 (t2,t3)
std::cout << "StackCount = " << Test::GetStackCount() << std::endl;//StackCount = 3 (t[3])
}
//Two heap objects are not deleted, but stack objects has been cleaned
std::cout << "HeapCount = " << Test::GetHeapCount() << std::endl;//HeapCount = 2
std::cout << "StackCount = " << Test::GetStackCount() << std::endl;//StackCount = 0
}