简体   繁体   中英

Logging allocator for std::containers?

The X: I need to know how much memory each part of my program is using. My program uses the C++ std library, a lot. 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

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:

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

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 :

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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