Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 338
gnzlbg Avatar asked Feb 19 '13 11:02

gnzlbg


1 Answers

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.

like image 188
Some programmer dude Avatar answered Sep 19 '22 02:09

Some programmer dude