diff options
Diffstat (limited to 'dbg_alloc.cc')
-rw-r--r-- | dbg_alloc.cc | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/dbg_alloc.cc b/dbg_alloc.cc new file mode 100644 index 0000000..c1b7490 --- /dev/null +++ b/dbg_alloc.cc @@ -0,0 +1,87 @@ +#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 <cassert> +#include <cstdio> +#include <cstdlib> + +template <typename T> +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 <typename U> + dbg_alloc(const dbg_alloc<U>&) { + } + + T* allocate(std::size_t size) noexcept { + assert(size > 0); + T* ptr = static_cast<T*>(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 <map> +#include <set> +#include <unordered_map> +#include <unordered_set> +#include <vector> + +int main() { + { + puts("-- std::vector"); + std::vector<int, dbg_alloc<int>> o; + for (int i = 0; i < 5; ++i) { + o.push_back(i); + } + } + { + puts("-- std::set"); + std::set<int, std::less<int>, dbg_alloc<int>> o; + for (int i = 0; i < 5; ++i) { + o.insert(i); + } + } + { + puts("-- std::unordered_set"); + std::unordered_set<int, std::hash<int>, std::equal_to<int>, dbg_alloc<int>> + o; + for (int i = 0; i < 5; ++i) { + o.insert(i); + } + } + { + puts("-- std::map"); + std::map<int, int, std::less<int>, dbg_alloc<std::pair<const int, int>>> o; + for (int i = 0; i < 5; ++i) { + o[i] = i * 2; + } + } + { + puts("-- std::unordered_map"); + std::unordered_map<int, int, std::hash<int>, std::equal_to<int>, + dbg_alloc<std::pair<const int, int>>> + o; + for (int i = 0; i < 5; ++i) { + o[i] = i * 2; + } + } +} |