Is there a portable C++-ish way to get a properly aligned pointer to an
object of given type from given arbitrary pointer-to-char?
As others in this thread have pointed out, there are two parts to this
problem. The first is determining what the alignment of T should be in
the first place, and the second is actually aligning a pointer to that
boundary. For the first part, Alf Steinbach provided a nice solution
here on the list, and there is also a slightly different solution is
available at [1].
Solving the second part is a bit trickier, since there is no assurance
that casting a pointer to an int will do anything useful. I believe I
have found a completely-portable solution, though. The solution relies
on two facts:
a) Arithmetic is well-defined between pointers in the same array
b) new[] returns memory which meets the platform's worst-case
alignment requirements
From the problem description, it sounds like the original poster is
allocating a large block of memory and then packing several smaller
items into that block. If that is the case, performing the alignment
relative to the block's starting address should always work. If the
block's starting address comes from new[], it will already meet the
platform's worst-case alignment requirements. Subtracting the start of
the block form a pointer into the block will yield a well-behaved
signed integer, which can then be aligned. Adding the integer back to
the start of the block will yield a pointer, as desired:
#define ALIGN(p, base, align) base + (p - base + (align-1) &
~(align-1))
Here, p is the pointer to align, base is the starting address of the
block, and align is the requested alignment. Both p and base are char
*'s. This macro should work even on platforms with "weird" pointer
representations, since it uses pointer arithmetic rather than directly
twiddling the pointer's bits.