1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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;
}
}
}
|