For reference, I am reading from "Game Engine Architecture 2nd Edition" by Jason Gregory.
Although I understand the theory behind Stack Allocators, I am having trouble implementing it fully. The book goes over Stack-Based Allocators and here is what I have so far in terms of code.
Memory.h file:
#pragma once
#include <iostream>
#include <stack>
typedef std::uint8_t U8;
typedef std::uint16_t U16;
typedef std::uint32_t U32;
typedef std::uintptr_t Marker;
class StackAllocator
{
public:
explicit StackAllocator(U32 nBytes); // Allocate all the memory that will be needed
Marker getMarker();
void* allocateUnaligned(U32 nBytes);
void clear();
void freeToMarker(const Marker& marker);
private:
void* bufferptr; // Start of memory allocated from heap
U32 nBytes; // How large the allocated memory is in # of bytes
};
Memory.cpp file:
#include "Memory.h"
//Stack Allocator
StackAllocator::StackAllocator(U32 nBytes)
: bufferptr(malloc(nBytes))
, nBytes(nBytes)
{}
Marker StackAllocator::getMarker()
{
}
void* StackAllocator::allocateUnaligned(U32 nBytes)
{
}
void StackAllocator::clear()
{
}
void StackAllocator::freeToMarker(const Marker &marker)
{
}
Admittedly, a lot of this code is copied from the book which is probably why I am confused. Jason Gregory says in the book.
"To ensure this is done properly, a stack allocator often provides a function that returns a marker representing the current top of the stack. The roll-back function then takes one of these markers as its argument."
So either I am completely stupid or there is a contradiction. In the book, he implements the getMarker() function and the freeToMarker(Marker marker) function in the same class, so which scope is managing the markers for the Stack Allocator? Is the class scope supposed to manage a marker stack or is the scope of whatever is calling it supposed to manage a marker stack. Is there even supposed to be a marker stack? He later says that you shouldn't free from arbitrary locations which makes sense but his solution was to roll back all the markers. Where are all of the markers supposed to be stored? From what it looks like, it should be the class scope but then why would the freeToMarker(Marker marker) function take a Marker as one of its arguments if it is already inside the class as a private member. Is this just a mistake by the author or am I missing something important?
P.S: None of the functions are implemented except for the constructor because I am confused about the whole Marker situation