Is reading an inactive member of a union of the same type as active, clearly defined?

Consider the following structure:

struct vec4 { union{float x; float r; float s}; union{float y; float g; float t}; union{float z; float b; float p}; union{float w; float a; float q}; }; 

Something like this seems to be used in, for example, GLM , to provide GLSL type types like vec4 , vec2 , etc.

But although the intended use seems to make it possible

 vec4 a(1,2,4,7); ax=7; ab=ar; 

this is similar to undefined behavior because, as stated here ,

In a union, not more than one data member can be active at any time, that is, the value of not more than one of the data elements can be stored in the union at any time.

Isn't it better, for example, to use just define a structure something like the following?

 struct vec4 { float x,y,z,w; float &r,&g,&b,&a; float &s,&t,&p,&q; vec4(float X,float Y,float Z,float W) :x(X),y(Y),z(Z),w(W), r(x),g(y),b(z),a(w), s(x),t(y),p(z),q(w) {} vec4() :r(x),g(y),b(z),a(w), s(x),t(y),p(z),q(w) {} vec4(const vec4& rhs) :x(rhs.x),y(rhs.y),z(rhs.z),w(rhs.w), r(x),g(y),b(z),a(w), s(x),t(y),p(z),q(w) {} vec4& operator=(const vec4& rhs) { x=rhs.x; y=rhs.y; z=rhs.z; w=rhs.w; return *this; } }; 

Or am I working on a problem that doesn't exist? Could there be some kind of special statement allowing access to identical types of inactive members of an association?

+6
source share
1 answer

I think that the quote in which you speak is aimed at different types of union.

 struct foo { union { float x, int y, double z, }; }; 

This is different data, conveniently stored in the same structure, and unions should not be involved.

The GLM approach uses the same data and uses union for the mechanics of aliases.

Your approach may be “better” with C ++, but worse than Engineering. Vector math should be fast, and the smaller the better.

Your implementation makes the vector 3 times larger. sizeof(glm::vec4); // 16 sizeof(glm::vec4); // 16 while sizeof(your_vec4); // 48 - ouch sizeof(your_vec4); // 48 - ouch If you process a large supply of them, which often happens, 3 times more misses in the cache with your_vec4 .

I think you are right, although using Jom as an alias is a bit, while I'm not sure that it is undefined, but this type of thing that I saw a lot, without any problems, and glm is widely used.

I really don't see the need to emulate glsl in C ++, but struct { float x,y,z,w; } struct { float x,y,z,w; } would be better (at least in my opinion).

-1
source

Source: https://habr.com/ru/post/989080/


All Articles