tags:

views:

87

answers:

1

What is the best way to count the total number of objects created in both stack and heap for different classes. I know that in C++ new and delete operators can be overloaded and hence in the default constructor and destructor the object count can be incremented or decremented as and when the objects get created or destroyed.

Further if i am to extend the same thing for object counting of objects of different classes, then i can create a dummy class and write the object count code in that class and then when i create any new class i can derive it from the Dummy class.

Is there any other optimal solution to the same problem.

+4  A: 

then i can create a dummy class and write the object count code in that class and then when i create any new class i can derive it from the Dummy class.

Yes, but since each class needs its own count, you have to make a base class template and use the curiously recurring template pattern (CRTP):

template <class Derived>
class InstanceCounter
{
    static int count;

protected:

    InstanceCounter()
    {
        ++count;
    }

    ~InstanceCounter()
    {
        --count;
    }

public:

    static int instance_count()
    {
        return count;
    }
};

template <class Derived>
int InstanceCounter<Derived>::count = 0;

class Test : public InstanceCounter<Test>
{
};

int main()
{
    Test x;
    std::cout << Test::instance_count() << std::endl;
    {
        Test y;
        Test z;
        std::cout << Test::instance_count() << std::endl;
    }
    std::cout << Test::instance_count() << std::endl;
}
FredOverflow