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)!
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 );
    }
};
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With