簡體   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