Logarithmic distributor for std :: containers?
X: I need to know how much memory each part of my program is using. My program uses the std C ++ library a lot. Specifically, I want to know how much memory each object is using.
How I do it: to record consumption some_vector
, just write
my::vector<double,MPLLIBS_STRING("some_vector")> some_vector;
Where
namespace my {
template<class T, class S>
using vector = std::vector<T,LoggingAllocator<T,S>>;
}
The logarithm distributor is implemented as follows:
template<class T, class S = MPLLIBS_STRING("unknown")> struct LoggingAllocator {
// ... boilerplate ...
pointer allocate (size_type n, std::allocator<void>::const_pointer hint = 0) {
log_allocation(boost::mpl::c_str<S>::value);
// allocate_memory (I need to handle it myself)
}
void destroy (pointer p) ; // logs destruction
void deallocate (pointer p, size_type num); // logs deallocation
};
Question: Is there a better way to get this behavior in general? For the best I mean, simpler, nicer, no dependencies on boost::mpl
and mpllibs::metaparse
, ... Ideally, I would just like to write
my::vector<double,"some_vector"> some_vector;
and get it over with.
source to share
While perhaps not "more general", if you don't want to handle the entire allocation yourself, you can inherit from the standard allocator std::allocator
:
template<class T, class S = MPLLIBS_STRING("unknown"), class Allocator = std::allocator<T>>
struct LoggingAllocator : public Allocator {
// ...
};
The functions allocate
/ destroy
/ deallocate
do the logging and then call the parent methods:
pointer allocate (size_type n, std::allocator<void>::const_pointer hint = 0) {
log_allocation(boost::mpl::c_str<S>::value);
return Allocator::allocate(n, hint);
}
Note, however, that std::allocator
it is not really intended for inheritance, an example of which is the lack of a virtual destructor.
source to share