Fork me on GitHub

Create your own allocator

The example is showing below.

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

template <class T>
class TrackingAllocator{
public:
using value_type = T;

using pointer = T *;
using const_pointer = const T *;

using void_pointer = void *;
using const_void_pointer = const void*;

using size_type = size_t;

using difference_type = std::ptrdiff_t;

TrackingAllocator() = default;
~TrackingAllocator() = default;

size_type get_allocations() {
return mAllocations;
}

pointer allocate(size_type num_objects) {
return static_cast<pointer>(operator new(sizeof(value_type)*num_objects));
}

void deallocate(pointer p, size_type num_objects) {
operator delete(p);
}

size_type max_size() const{
return std::numeric_limits<size_type>::max();
}
private:
static size_type mAllocations;
};

template <class T>
typename TrackingAllocator<T>::size_type TrackingAllocator<T>::mAllocations = 0;

int main () {
std::vector<int, TrackingAllocator<int> > v(5);
return 0;
}