From reading various other Stack Overflow questions, it seems that double
values may sometimes only be 4-byte aligned instead of 8 (hence the existence of GCC's -malign-double
). Does this apply to the heap as well as the stack?
It seems to me that if double
values on the heap were not always 8-byte aligned, then it would be impossible to perform pointer arithmetic with double*
values since incrementing a double*
advances it by 8 bytes, but the difference between two arbitrary double*
values might not be a multiple of 8 bytes.
If you're curious about the use case I'm interested in, I have something like:
#include <iostream>
#include <iostream>
#include <vector>
struct EmptyBase1
{
};
struct EmptyBase2
{
};
struct Point : public EmptyBase1, public EmptyBase2
{
double x;
double y;
double z;
};
int main() {
std::vector<Point> points(10);
int stride = &points[1].x - &points[0].x;
std::cout << stride << std::endl;
return 0;
}
Visual Studio does not fully apply the empty base class optimization in this case (see https://stackoverflow.com/a/12714226/953078), so it is not guaranteed that sizeof(Point) == 3 * sizeof(double)
. Is stride
guaranteed to always give a valid memory offset between &points[1].x
and &points[2].x
, &points[5].y
and &points[4].y
etc.?