繁体   English   中英

记录std :: containers的分配器?

[英]Logging allocator for std::containers?

X:我需要知道我的程序的每个部分使用了多少内存。 我的程序使用了很多C ++ std库。 特别是,我想知道每个对象使用多少内存。

我是怎么做的:记录some_vector的消耗,只需写

my::vector<double,MPLLIBS_STRING("some_vector")> some_vector;

哪里

namespace my {
  template<class T, class S>
  using vector = std::vector<T,LoggingAllocator<T,S>>;
}

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
};

问题:是否有更好的方法以通用方式获得此行为? 通过更好,我的意思是,更简单,更好,没有依赖boost::mplmpllibs::metaparse ,...理想情况下我只想写

my::vector<double,"some_vector"> some_vector;

并完成它。

虽然可能不是“更通用”,但如果您不想自己处理所有分配,则可以继承标准分配器std::allocator

template<class T, class S = MPLLIBS_STRING("unknown"), class Allocator = std::allocator<T>>
struct LoggingAllocator : public Allocator {
    // ...
};

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);
}

但请注意, std::allocator并非真正设计用于继承,例如它没有虚拟析构函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM