Simplest way to count instances of an object

后端 未结 8 1905
时光取名叫无心
时光取名叫无心 2021-01-01 17:42

I would like to know the exact number of instances of certain objects allocated at certain point of execution. Mostly for hunting possible memory leaks(I mostly use RAII, al

相关标签:
8条回答
  • 2021-01-01 18:31

    Better off to use memory profiling & leak detection tools like Valgrind or Rational Purify.

    If you can't and want to implement your own mechanism then,

    You should overload the new and delete operators for your class and then implement the memory diagnostic in them.

    Have a look at this C++ FAQ answer to know how to do that and what precautions you should take.

    0 讨论(0)
  • 2021-01-01 18:31

    This is a sort of working example of something similar: http://www.almostinfinite.com/memtrack.html (just copy the code at the end of the page and put it in Memtrack.h, and then run TrackListMemoryUsage() or one of the other functions to see diagnostics)

    It overrides operator new and does some arcane macro stuff to make it 'stamp' each allocation with information that allow it to count how many instances of an object and how much memory they're usingusing. It's not perfect though, the macros they use break down under certain conditions. If you decide to try this out make sure to include it after any standard headers.

    0 讨论(0)
提交回复
热议问题