Is this valid/portable/legal code:
class Vector3
{
public:
float& operator [] ( const size_t i )
{
assert( i < 3 );
return *(&x+i);
}
float x, y, z;
};
There have been quite a few instances where I wanted to use the [] operator and ended up putting the elements in an array (to avoid if/switch statements). I never did what is being done in this particular method. I can tell why it works (x,y and z are contiguous) but is it good (or at least ok) practice?
Also, does the code require #pragma pack 1 to guarantee no-pad packing or can it work without it? Reason I ask is because the snippet is actually taken from Ogre3D vector class and I don’t see #pragma pack 1 anywhere.
No. This is not correct and is not good practice. It is likely that there won’t be padding between the three elements (even without instructing the compiler to pack the structure) and thus it is likely that you would be able to access the members as if they were elements of an array. That doesn’t make the code right, though: the code as written yields undefined behavior.
A correct way to do this would be to use accessor functions for the components, e.g.