I’m writing a slice allocator in C++98. The allocator will consist of two template classes:
- Low-level allocator class which would allocate the actual memory,
- High-level allocator class which will wrap requested objects as
char[]arrays of appropriate length.
I would like to know whether the assumptions I make below about alignment are valid.
First of all, I assume that within an array of objects (of type T), each object is properly aligned. I don’t see anything specific about that in the standard but it seems like a reasonable assumption to me.
Considering that, if I take sizeof(T[n]), the returned size should contain any padding necessary and thus be suitable for storing the array T[n].
Secondly, 18.4.1.1 (operator new) states:
1 Effects: The allocation function (3.7.3.1) called by a new-expression (5.3.4) to allocate
sizebytes of storage suitably aligned to represent any object of that size.
Thus, I assume that ::operator new(sizeof(T[n])) should create a memory block suitably aligned for the array T[n].
Finally, 9.2 (class members) states:
17 A pointer to a POD-struct object, suitably converted using a
reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [Note: There might therefore be unnamed padding within a POD-struct object, but not at its beginning, as necessary to achieve appropriate alignment. ]
Thus, I would assume that in a struct like:
struct node
{
char data[sizeof(T[n])];
node* next;
};
allocated via new node, the data member will be properly aligned for the array T[n].
Are the above assumptions correct or am I missing something? I believe that I have to implement the linked list manually since the C++ standard doesn’t give any guarantees about node member order.
Yes, your assumptions are correct. I may have missed something but I don’t get why you can’t have something like this: