-
Notifications
You must be signed in to change notification settings - Fork 0
/
new-expression-with-allocator.cc
85 lines (69 loc) · 1.47 KB
/
new-expression-with-allocator.cc
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
#include <cstdio>
#include <memory>
struct use_allocator_t {
explicit use_allocator_t() = default;
};
template <class A>
void* operator new(size_t size, use_allocator_t, A a)
{
using traits = std::allocator_traits<A>;
return traits::allocate(a, size);
}
template <class A>
void* operator new[](size_t size, use_allocator_t, A a)
{
using traits = std::allocator_traits<A>;
return traits::allocate(a, size);
}
template <class A>
void operator delete(void* p, use_allocator_t, A a)
{
using traits = std::allocator_traits<A>;
return traits::deallocate(a, p);
}
template <class A>
void operator delete[](void* p, use_allocator_t, A a)
{
using traits = std::allocator_traits<A>;
return traits::deallocate(a, static_cast<typename traits::pointer>(p), 0);
}
template <class T>
struct barfing_allocator {
using value_type = T;
T* allocate(size_t size)
{
printf("allocate %lu\n", size);
return static_cast<T*>(::operator new(size));
}
void deallocate(T* p, size_t)
{
printf("deallocate\n");
return ::operator delete(p);
}
};
struct fail_halfway {
static size_t counter;
size_t idx;
fail_halfway()
: idx(++counter)
{
printf("I am %lu\n", idx);
if (idx == 5)
throw 42;
}
~fail_halfway()
{
printf("%lu dying\n", idx);
}
};
size_t fail_halfway::counter = 0;
int main()
{
barfing_allocator<fail_halfway> a;
try {
new (use_allocator_t(), a) fail_halfway[10];
} catch(int) {
return 0;
}
return 1;
}