Re: wrapping std::vector<> to track memory usage?
On Sep 30, 3:00 pm, jacek.dzied...@gmail.com wrote:
I need to be able to track memory usage in a medium-sized
application I'm developing. The only significant (memory-wise) non-
local objects are of two types -- std::vector<> and of a custom class
simple_vector<> that is a hand-rolled substitute for array<>. With the
latter I have code that tracks all allocations and destructions, so I
can account for all the memory.
The question is about std::vector<> -- how can I track memory usage
by individual std::vector's? I'm thinking along the lines of a wrapper
(templated) class, like std::tracked_vector<> which would have the
original std::vector<> as a private member, delegate relevant
operations to the underlying std::vector, while doing the accounting
job behind the scenes.
[]
You could use a custom allocator that would maintain a counter of how
much memory has been allocated. Something like that:
#include <vector>
#include <iostream>
size_t allocated;
void print_allocated(int n)
{
std::cout << n << ": " << allocated << '\n';
}
template<class T>
struct counted_allocator : std::allocator<T>
{
template<class U>
struct rebind { typedef counted_allocator<U> other; };
typedef std::allocator<T> base;
typedef typename base::pointer pointer;
typedef typename base::size_type size_type;
pointer allocate(size_type n)
{
allocated += n * sizeof(T);
return this->base::allocate(n);
}
pointer allocate(size_type n, void const* hint)
{
allocated += n * sizeof(T);
return this->base::allocate(n, hint);
}
void deallocate(pointer p, size_type n)
{
allocated -= n * sizeof(T);
this->base::deallocate(p, n);
}
};
int main()
{
typedef std::vector<int, counted_allocator<int> > IntVec;
print_allocated(0);
{
IntVec v;
v.resize(1000);
print_allocated(1);
v.resize(2000);
print_allocated(2);
IntVec u = v;
print_allocated(3);
}
print_allocated(4);
}
Output:
0: 0
1: 4000
2: 8000
3: 16000
4: 0
--
Max