-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackAllocator.h
45 lines (36 loc) · 983 Bytes
/
StackAllocator.h
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
#pragma once
#include <cassert>
#include "Allocator.h"
/*
* Fixed size stack allocator. Memory should be deallocated LIFO order.
* Destroys itself once the first allocated segment is deallocated.
*/
class StackAllocator : public Allocator {
public:
void* allocate(size_t size) {
if (ptr_ - size <= buffer_ - size_) {
return nullptr;
}
return ptr_ -= size;
}
void deallocate(void* ptr, size_t size) {
assert(ptr == ptr_);
ptr_ += size;
if (ptr_ == buffer_) {
delete this;
}
}
static StackAllocator* create(size_t size) {
auto ptr = static_cast<StackAllocator*>(malloc(sizeof(StackAllocator) + size));
new (ptr)StackAllocator(size, ptr + 1);
return ptr;
}
StackAllocator(const StackAllocator&) = delete;
StackAllocator& operator=(const StackAllocator&) = delete;
private:
StackAllocator(size_t size, void* buffer)
: buffer_(static_cast<char*>(buffer) + size), ptr_(buffer_), size_(size) {}
char* buffer_;
char* ptr_;
size_t size_;
};