Skip to content
Snippets Groups Projects
Commit 9e485bb8 authored by j2-pelczar's avatar j2-pelczar :cowboy:
Browse files

Upload New File

parent 43a39eac
No related branches found
No related tags found
No related merge requests found
#ifndef BUMP_ALLOCATOR_HPP
#define BUMP_ALLOCATOR_HPP
#include <cstddef>
#include <iostream>
class BumpAllocator {
private:
char* memory;
char* next;
std::size_t capacity;
std::size_t used;
public:
explicit BumpAllocator(std::size_t size)
: memory(new char[size]), next(memory), capacity(size), used(0) {}
~BumpAllocator() {
delete[] memory;
}
template <typename T>
T* alloc(std::size_t count = 1) {
std::size_t requiredBytes = count * sizeof(T);
if (next + requiredBytes > memory + capacity) {
std::cerr << "Out of memory: cannot allocate " << requiredBytes << " bytes.\n";
return nullptr;
}
T* allocation = reinterpret_cast<T*>(next);
next += requiredBytes;
++used;
return allocation;
}
void dealloc() {
if (used > 0) {
--used;
if (used == 0) {
next = memory;
}
} else {
std::cerr << "Error: No allocations to deallocate.\n";
}
}
void printStatus() const {
std::cout << "Allocator status:\n";
std::cout << " Capacity: " << capacity << " bytes\n";
std::cout << " Used: " << (next - memory) << " bytes\n";
std::cout << " Allocations: " << used << "\n";
}
};
#endif
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment