I understand I can provide a custom allocator for most of the stl containers. If I record memory allocations in this custom allocator, then I can keep track of memory allocations. For example, with the help of MyAllocator in std::vector<T, MyAllocator<T>>
, we can alway tell how much memory is consumed by this vector.
However, such allocators only applies to stl containers. If we want to keep track of a custom class, we have to come up with some other ideas.
One idea is that we can override operator new
and operator new []
. However, there are some drawbacks:
operator new
andoperator new []
apply only to allocations by thenew
operators, which usually allocates on heap. Ok, maybe this is not too much a problem since we cares heap memory the most.operator new
andoperator new []
do not apply to dynamic memory allocations inside the class. For example, given typeT
, if I allocated some memory bya = new R [10000]
inT::T()
, then such memory allocation will not be tracked byoperator new
andoperator new []
.- Talk more about the upper case. There is problem even if I have also implemented
R
‘soperator new
. Because it only allows me to summery how much memoryT
allocates, and how much memoryR
allocates respectively. However what I want to know is how much memoryT
allocates including all its fields at some timepoint. That means if I calleda = new R [10000]
, then I can somehow find the instance ofT
has allocatedsizeof(T)
+sizeof(R) * 1000
, rather than that the instance ofT
has allocatedsizeof(T)
and another 1000 instances ofR
has allocatedsizeof(R)
.
So I wonder how to do that.