X: 我需要知道程序的每个部分使用了多少内存。我的程序大量使用C++标准库。特别是,我想知道每个对象使用了多少内存。
我如何做到这一点:要记录some_vector
的消耗,只需编写:
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>>;
}
登录分配器的实现如下:
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
};
问题:有没有更好的通用方法来实现这种行为?我所说的更好是指,更简单、更好、不依赖于boost::mpl
和mpllibs::metaparse
等库。理想情况下,我只想写下面的代码:
my::vector<double,"some_vector"> some_vector;
并且完成它。