struct A
{
int a = 1;
short b = 2;
char c = 3;
}
struct B
{
using arr_type = array<A,3>;
char asd = 0;
A a1;
A a2;
A a3;
// is this safe to use to loop trough all 3 elements?
arr_type* p1 = reinterpret_cast<arr_type*>(&a1);
// or maybe this one?
A* p2 = &a1;
};
Can I safely use p1
or p2
to loop from a1...a3
?
B b;
for (int i = 0; i < 3; i++)
{
cout << p1[i];
cout << p2[i];
}
The reason why it's not a simple array is because I want each "item" to have a proper name.
I could instead use the union approach, but the C++ prohibits anonymous structs (altho this is not a problem for me since MSVC supports this and GCC seems to support it as well);
union E
{
A arr[3];
struct {
A a1;
A a2;
A a3;
};
};
And the following is clearly safe, but it has a 4 byte overhead for each reference. Which I don't like. (Plus the cost to initialize the references..)
struct B
{
char asd;
A arr[3];
A& a1 = arr[0];
A& a2 = arr[1];
A& a3 = arr[2];
};
And this one has no overhead but for my very specific case, it's not good enough.
struct B
{
char asd;
A arr[3];
A& a1() { return arr[0] };
A& a2() { return arr[1] };
A& a3() { return arr[2] };
};
I'm gonna be using those a1, a2, a3
names very often, and it's harder to debug them if they are function calls in visual studio. And again, I'm going to be using those fields a lot, so I want to be able to check their values easily.