What is the best or conventional method to align members inside a structure? Is adding dummy arrays the best solution?
I have a struct of double and a triple of doubles?
struct particle{
double mass;
std::tuple<double, double, double> position;
}
If I have an array of these, the memory will look like this
[d][d d d][d][d d d][d][d d d]...
The problem is that the distance from the first triple to the second triple is not an integer multiple of sizeof(std::tuple<double, double,double>)==3*sizeof(double), therefore I cannot interpret the interleaved array of triples as an array with strides.
What is the best method to force the triple to have a different offset?
I could stick a number of artificial doubles in the middle to match the offset:
struct particle{
double mass;
double garbage[2];
std::pair<double, double> position;
}
So memory will look like this
[d][* *][d d][d][* *][d d][d][* *][d d]...
but then I cannot use initializers (particle{1.,{1.,2.}}).
I could also add it to the end
struct particle{
double mass;
std::pair<double, double> position;
double garbage[2];
}
So, I can keep using the initializer. Is this the best method? But it will only work in this simple case.
Another alternative could be to force alignment of the struct to some multiple of the 3*sizeof(double)
struct alignas(3*sizeof(double)) particle{double mass; std::tuple<...> position;};
but the problem is that it is not a power of 2, so GCC and clang reject it. Note that in other sizes of the tuple the alignas strategy works because it can solve the problem being accidentally a power of two.
For example
struct alignas(4*sizeof(double)) particle{double mass; std::pair<double, double> position;};
Is there a general or accepted solution for this?
I also found about ((packed)), is that also necessary in this solution?
Aucun commentaire:
Enregistrer un commentaire