example3_custom_allocator.cpp

 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
#include <iostream>
#include <memory>
#include <vector>

template <typename T>
class TrackingAllocator : public std::allocator<T> {
public:
    using size_type = size_t;
    using pointer = T*;
    using const_pointer = const T*;

    template <typename U>
    struct rebind {
        typedef TrackingAllocator<U> other;
    };

    pointer allocate(size_type n, const void* hint = 0) {
        std::cout << "Allocating " << n << " objects\n";
        return std::allocator<T>::allocate(n, hint);
    }

    void deallocate(pointer p, size_type n) {
        std::cout << "Deallocating " << n << " objects\n";
        std::allocator<T>::deallocate(p, n);
    }
};

int main() {
    std::vector<int, TrackingAllocator<int>> v;
    for (int i = 0; i < 10; ++i) {
        v.push_back(i);
    }
    return 0;
}
Back to memory