Naming Array Elements, or Struct And Array Within a Union

前端 未结 4 1805
梦毁少年i
梦毁少年i 2021-01-17 13:50

Consider the following struct:

struct Vector4D
{
   union
   {
      double components[4];
      struct { double x, y, z, t; } Endpoint;
   };
};


        
相关标签:
4条回答
  • 2021-01-17 14:00

    Padding bytes will not cause an issue as all variables are of type double. The compiler will treat Vector4D as a double array. That means, v.Endpoint.z is essentially the same as v[2].

    0 讨论(0)
  • 2021-01-17 14:01

    You can circumvent any memory alignment issues by having references to each element of the array, as long as you declare the array before the references in the class to ensure they point to valid data. Having said that I doubt alignment would be an issue with doubles, but could be for other types (float on 64bit arch perhaps?)

    #include <iostream>
    using namespace std;
    
    struct Vector4D
    {
        Vector4D() : components(), x(components[0]), y(components[1]), z(components[2]), t(components[3]) { }
    
        double components[4];
    
        double& x;
        double& y;
        double& z;
        double& t;
    };
    
    int main()
    {
        Vector4D v;
    
        v.components[0] = 3.0;
        v.components[1] = 1.0;
        v.components[2] = 4.0;
        v.components[3] = 15.0;
    
        cout << v.x << endl;
        cout << v.y << endl;
        cout << v.z << endl;
        cout << v.t << endl;
    }
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-17 14:06

    When it comes to the standard, there are two problems with it:

    • It is unspecified what happens when writing to an element in a union and reading from another, see the C standard 6.2.6.1 and K.1
    • The standard does not guarantee the layout of the struct match that of the layout of the array, see the C standard 6.7.2.1.10 for details.

    Having said this, in practice this will work on normal compilers. In fact, this kind of code is widely spread and is often used to reinterpret values of one type into values of another type.

    0 讨论(0)
  • 2021-01-17 14:22
    1. yes
    2. depends on the alignment needs of the architecture and the compilers strategy
    3. no, but you could make a object wrapper (but you will end up with .z() instead of just .z)

    Most compilers should support squashing a structure using a pragma or an attribute. #pragma pack for example.

    0 讨论(0)
提交回复
热议问题