Finding memory usage of one class in C ++

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

Is there a way to do this without changing the source code (i.e. using tools like valgrind)?

And what methods can I use to do this by changing the source code (I cannot change the creation of each instance, but I can change 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)!

+4
source share
2 answers

It is very easy to overload operator new() in the class. The global can be called with :: to specify the global namespace, as in ::operator new() . Something like that:

 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 ); } }; 
+4
source

If you want to track the space used by objects on the stack, you better add tracking to the constructor and destructor. Something like this should do the job. Only potential problem is that there may be dynamically allocated elements 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; } 
+3
source

Source: https://habr.com/ru/post/1386647/


All Articles