Re: Operator: alignof
* Frederick Gotham:
It is possible and permissible on a given system, that the alignment
requirements of a type are less than the size of that type. For instance,
here's a hypothetical set-up:
int is 4 bytes, but need only be aligned on a 2 byte boundary.
Yes, of course: for most types and platforms alignment is less than the
size of an object of the type.
C++ as a language does not address alignment.
Alignment requirements arise from the hardware (system bus, memory
interface) and from the OS (some can fix alignment faults, at cost, and
in Windows this can be configured).
If we had some sort of "alignof" operator, then we would be able to do
the following:
int main()
{
int array[2];
int *p = array;
/* The following function is defined elsewhere. I use it
here to make this snippet as simple as possible. */
AdvancePointerByBytes( p, alignof(int) );
*p = 5;
}
What are you trying to do? 'array' is already suitably aligned for
'int'. Also, advancing a pointer by the alignment value for a type
doesn't make the pointer well-aligned for that type. Instead you need
to treat the address as an integer and advance it to the next multiple
of the alignment value, if not already at such multiple. Like
typedef unsigned long ulong; // Assuming ulong is enough.
char array[1000];
ulong const a = (ulong)(&a[0]) + alignment(int) - 1; // ...
int* p = (int*)(a - a%alignment(int));
which for 2^x alignment is usually done by bit-operations.
Over on comp.lang.c, Hallvard B Furuseth devised such an operator, and a
lot of people use it.
I've adapted it to C++, and I've written a sample program consisting of
two headers and one source file. Any thoughts on it?
/* BEGINNING OF advance_ptr.hpp */
#ifndef INCLUDE_ADVANCE_PTR_HPP
#define INCLUDE_ADVANCE_PTR_HPP
#include <cstddef>
template<class T>
inline void AdvancePtr( T * &p, std::size_t const bytes )
{
p = reinterpret_cast< T* >(
const_cast<unsigned char *>(
reinterpret_cast<const unsigned char *>(p) + bytes
)
);
}
This is IMO mixing incompatible levels of abstraction. Alignment is
part of low-level functionality where you don't really care about the
type T that the pointer will finally end up pointing to. It's IMO
Ungood and almost Evil(TM) to offer client code "easy" functionality to
mix such low-level things with higher level code.
Although I haven't used it, on general grounds I recommend you take a
look at the Boost utility referenced else-thread.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?