Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)!

like image 420
Karan Avatar asked Feb 22 '23 02:02

Karan


1 Answers

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 );
    }
};
like image 191
sharptooth Avatar answered Mar 08 '23 11:03

sharptooth