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函数中进行日志记录,然后调用parent方法:
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并不是真正为继承而设计的,例如,它没有虚拟析构函数。

09-04 18:17
查看更多