#if 0 set -xe trap "rm -f a.out" EXIT clang++ -std=c++17 dbg_alloc.cc && ./a.out g++ -std=c++17 dbg_alloc.cc && ./a.out exit 0 #endif #include #include #include template class dbg_alloc { inline static std::size_t INST_CNT = 0; std::size_t inst = INST_CNT++; public: using value_type = T; dbg_alloc() = default; template dbg_alloc(const dbg_alloc&) { } T* allocate(std::size_t size) noexcept { assert(size > 0); T* ptr = static_cast(std::calloc(sizeof(T), size)); std::fprintf(stderr, "[%2zu] alloc %8zu (%p)\n", inst, size, ptr); return ptr; } void deallocate(T* ptr, std::size_t size) noexcept { std::fprintf(stderr, "[%2zu] dealloc %8zu (%p)\n", inst, size, ptr); std::free(ptr); } }; // -- EXAMPLE ------------------------------------------------------------------ #include #include #include #include #include int main() { { puts("-- std::vector"); std::vector> o; for (int i = 0; i < 5; ++i) { o.push_back(i); } } { puts("-- std::set"); std::set, dbg_alloc> o; for (int i = 0; i < 5; ++i) { o.insert(i); } } { puts("-- std::unordered_set"); std::unordered_set, std::equal_to, dbg_alloc> o; for (int i = 0; i < 5; ++i) { o.insert(i); } } { puts("-- std::map"); std::map, dbg_alloc>> o; for (int i = 0; i < 5; ++i) { o[i] = i * 2; } } { puts("-- std::unordered_map"); std::unordered_map, std::equal_to, dbg_alloc>> o; for (int i = 0; i < 5; ++i) { o[i] = i * 2; } } }