Karan
Karan

Reputation: 559

Finding memory usage of a single class in c++

I have a class classX and would like to know how much how much memory all of the instances of this class use. Every new instance is created using new classX

Is there a way to do this without modifying source code (ie using tools like valgrind)?

And what methods can I use to do this by modifying the source code (I can't modify each instance creation, but can modify the class itself).
The only method I can think of is to overload the new operator (but I don't know how to call the original new operator from there)!

Upvotes: 4

Views: 3970

Answers (2)

Michael Anderson
Michael Anderson

Reputation: 73530

If you want to track space used by objects on the stack, you'd be better off adding your tracking in the constructor and destructor. Something like this should do the job. Only potential issue is that there may be dynamically allocated members that you need to track too.

class Tracked
{
   static int space_used;
   static int space_released;
   Tracked() { space_used += sizeof(Tracked); }
   ~Tracked() { space_released += sizeof(Tracked); }
};

int Tracked::space_used = 0;
int Tracked::space_released = 0;

int main()
{
   {
     Tracked t;
     Tracked * t_ptr = new Tracked();
   }

   std::cout<<"used      :"<< Tracked::space_used <<std::endl;
   std::cout<<"released  :"<< Tracked::space_released <<std::endl;
   std::cout<<"live      :"<< Tracked::space_used - Tracked::space_released <<std::endl;
}

Upvotes: 4

sharptooth
sharptooth

Reputation: 170509

It's quite easy to overload operator new() in the class. The global one can be then called using :: to specify global namespace as in ::operator new(). Something like this:

class ClassX {
public:
    void* operator new( size_t size )
    {
        // whatever logging you want
        return ::operator new( size );
    }
    void operator delete( void* ptr )
    {
        // whatever logging you want
        ::operator delete( ptr );
    }
};

Upvotes: 4

Related Questions