I’m reading through some C++ implementations for database objects and there’s a common theme - shared objects/pointers.
It’s a common question we get around pointers and people used to RAII - how to do shared memory where calling deinit
doesn’t invalidate other objects.
So this got me to thinking about trying to create an allocator or manager that handles this idea.
I’m only at the conceptual step here, so I’m sure I’m wrong and have a lot to learn, but that’s why I’m here (after all).
Here’s my first approximation for the allocator:
First, we’d have to track the memory that’s been allocated - that could be stored in some data-structure that’s favourable for quick lookup.
For any memory that’s allocated, we save a pointer to it along with a counter. For different pointer types, that info could be saved either as the numeric value of the pointer (like @intFromPtr
) and stored as a usize or even as an *anyopaque
. That would have to happen with the alloc
function.
When the user calls free
, the item would be located and the associated counter is decremented. When counter reaches zero, the item can then be actually freed.
For resize
, that would require the counter to be equal to one - otherwise, it just returns false. That way, we don’t invalidate other memory currently pointed to that same address.
Cons
The first one being that objects that require reallocation frequently would be more expensive. Same thing goes for resizing - unless you’re positive that you only have one count, it would fail most of the time. If that’s the case, then you probably aren’t actually sharing objects, making the entire mechanism awkward.
The other alternative is to skip the allocator idea entirely and just build a struct
that wraps an allocator and provides an even more limited interface. One benefit here is we could omit resize entirely and communicate the intent more clearly.
Any thoughts?