diff options
author | Johannes Stoelp <johannes.stoelp@gmail.com> | 2024-07-02 21:08:45 +0200 |
---|---|---|
committer | Johannes Stoelp <johannes.stoelp@gmail.com> | 2024-07-02 21:08:45 +0200 |
commit | 0bb7c1ccf2fef23cbe0e263614fc4050b96305ea (patch) | |
tree | 88841c910b53b9a157b8dab135653eeaa7a40aee /dbg_alloc.cc | |
parent | 80da515cf77860bf47cb61d46e67e33db57e7bec (diff) | |
download | cpp-templates-0bb7c1ccf2fef23cbe0e263614fc4050b96305ea.tar.gz cpp-templates-0bb7c1ccf2fef23cbe0e263614fc4050b96305ea.zip |
alloc: minimal allocator for inspections
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; + } + } +} |