> Here, memory arrangement of the below class is arranged to be contiguous memory layout
> without alignment(no padding) based on C++ specification?
In theory, no. The only explicitly stated guarantee is that for standard layout types, the address of the object is the same as the address of its first non-static member object.
In practice, I would say yes. An implementation would introduce un-named padding within the object only if it is necessary for achieving correct alignment.
Note:
std::complex<T> is a special case; the standard explicitly states that it can safely be accessed as if it were an array of two T.
https://eel.is/c++draft/complex.numbers#general-4
> should I use array of floating type like double[3]?
Yes, That would be the clean option. With
1 2 3 4 5 6 7 8 9
|
struct VectorD {
double d[3] ;
double& x() { return d[0] ; }
const double& x() const { return d[0] ; }
// etc.
};
|
there is the guarantee that the address of the object is the same as the address of its array member (the first non-static member object). No extra instructions would be needed to access it as an array. The compiler obviously knowns the layout; even if it was not an array, the address + constexpr offset computation would be required anyway for accessing non-static members (other than the first one) of the class.