[英]Logging allocator for std::containers?
The X: I need to know how much memory each part of my program is using. X:我需要知道我的程序的每个部分使用了多少内存。 My program uses the C++ std library, a lot. 我的程序使用了很多C ++ std库。 In particular, I want to know how much memory each object is using. 特别是,我想知道每个对象使用多少内存。
How I'm doing it: to log the consumption of some_vector
, just write 我是怎么做的:记录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>>;
}
The loggin allocator is implemented as follows: loggin分配器实现如下:
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 a generic way? 问题:是否有更好的方法以通用方式获得此行为? By better I mean, simpler, nicer, without dependencies on boost::mpl
and mpllibs::metaparse
,... Ideally I would just like to write 通过更好,我的意思是,更简单,更好,没有依赖boost::mpl
和mpllibs::metaparse
,...理想情况下我只想写
my::vector<double,"some_vector"> some_vector;
and be done with it. 并完成它。
While maybe not "more generic", if you don't want to handle all the allocation yourself, you could inherit from the standard allocator std::allocator
: 虽然可能不是“更通用”,但如果您不想自己处理所有分配,则可以继承标准分配器std::allocator
:
template<class T, class S = MPLLIBS_STRING("unknown"), class Allocator = std::allocator<T>>
struct LoggingAllocator : public Allocator {
// ...
};
In the allocate
/ destroy
/ deallocate
functions do the logging, and then call the parents methods: 在allocate
/ destroy
/ deallocate
函数中执行日志记录,然后调用parents方法:
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);
}
However note that std::allocator
isn't really designed for being inherited, exemplified by it having no virtual destructor. 但请注意, std::allocator
并非真正设计用于继承,例如它没有虚拟析构函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.