I'm trying to make a memory pool class that allows me to return pointers from within a char* array, and cast them as various pointer. Very very simplified implementation:
class Mempool
{
char* mData=new char[1000];
int mCursor=0;
template <typename vtype>
vtype* New()
{
vtype* aResult=(vtype*)mData[mCursor];
mCursor =sizeof(vtype);
return aResult;
}
};
(Remember, it's not intended to be dynamic, this is just random access memory that I only need for a short time and then it can all be tossed)
Here's my issue: I know that on some systems (iOS, at least) a float* has to be aligned. I assume the alignment is obtained via alignof(float)... but I can't ever be sure of the alignment of the initial char*'s allocation could be anywhere, because alignof(char) is 1.
What can I do to make sure that in my New() function, my mCursor is advanced to a proper alignment for the requested object?
CodePudding user response:
alignof(std::max_align_t)
will tell you the alignment required on your platform for standard functions like malloc()
. You should use that if you don't know what alignment requirements the users of your allocator will have.
Simply round sizeof(vtype)
up to the nearest multiple of alignof(std::max_align_t)
when you increment mCursor
.
Or for perhaps a little more efficiency, increment mCursor
as you do now, then round it up as needed when the user requests an allocation. When allocating an object of size 2 for example, you know that 2-byte alignment is sufficient, you don't need the full alignof(std::max_align_t)
. You can use alignof(vtype)
for this, to avoid wasted space if users allocate small objects next to each other.
As for this:
I can't ever be sure of the alignment of the initial char*'s allocation could be anywhere, because alignof(char) is 1
You can be sure: new char[N]
will always be aligned to at least alignof(std::max_align_t)
. But my second approach (pad when New is called) does not rely on this assumption.