c++ - std::containers 的日志分配器?

标签 c++ memory-management c++11 boost-mpl allocator

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

登录分配器实现如下:

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 函数中进行日志记录,然后调用父方法:

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 并不是真正为继承而设计的,例如它没有虚拟析构函数。

关于c++ - std::containers 的日志分配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14956176/

相关文章:

c++ - 使用 Visual Studio 2012 编译时,此代码会出现错误,但使用代码块就可以了

c++ - 用作值的共享指针 - 赋值期间出错

c++ - 初始化一个 **Array 以及标题中实际需要的内容,以便它通过

c++ - 如何删除 STL 容器?

c++ - 按节点计算单链表中的出现次数

c++ - 为什么这段代码会泄露?

c++ - 如何知道某个指针是否已在其他地方释放

java - java中如何避免在循环中频繁创建对象?

c++ - 如何在 for_each 中使用 lambda?

c++ - 为什么 std::make_pair 不返回一对?或者是吗?