-
Notifications
You must be signed in to change notification settings - Fork 0
/
alloc.cpp
92 lines (60 loc) · 1.69 KB
/
alloc.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
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
88
89
90
91
92
#include <memory>
#include <cstddef>
#include <iostream>
struct header {
std::size_t magic = 1234567890;
header() {
std::clog << __func__ << " " << this << std::endl;
}
~header() {
std::clog << magic << std::endl;
std::clog << __func__ << " " << this << std::endl;
}
};
struct item {
item() {
std::clog << __func__ << " " << this << std::endl;
}
~item() {
std::clog << __func__ << " " << this << std::endl;
}
};
template<class H, class T>
struct variable {
struct base {
H header;
T body[0];
};
struct boxed {
T value;
static void* operator new[](std::size_t count) {
void* ptr = std::malloc( sizeof(base) + count );
// initialize control block
base* b = new (ptr) base;
std::clog << "new: " << b << " " << b->body << std::endl;
return b->body;
};
static void operator delete[](void* ptr, std::size_t size) {
std::clog << "delete: " << ptr << std::endl;
base* block = reinterpret_cast<base*>((char*)ptr - offsetof(base, body));
// finalize control block
block->~base();
std::free(block);
}
friend const H& head(const boxed* self) {
const base* block = reinterpret_cast<const base*>((const char*)self - offsetof(base, body));
return block->header;
}
friend H& head(boxed* self) {
base* block = reinterpret_cast<base*>((char*)self - offsetof(base, body));
return block->header;
}
};
};
int main(int, char**) {
using type = variable<header, item>;
type::boxed* test = new type::boxed[14];
std::clog << head(test).magic << std::endl;
delete [] test;
return 0;
}