c++ - Is reading inactive union member of the same type as active one well-defined? -


this question has answer here:

consider 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 seems used in e.g. glm provide glsl-like types vec4, vec2 etc..

but although intended usage make possible

vec4 a(1,2,4,7); a.x=7; a.b=a.r; 

, seems undefined behavior, because, quoted here,

in union, @ 1 of data members can active @ time, is, value of @ 1 of data members can stored in union @ time.

wouldn't better e.g. use define structure 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 working around non-existent issue? there maybe special statement allowing access identically-typed inactive union members?

i think quote in referring directed @ having different types in union.

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

these different data, conveniently stored same structure, unions not supposed casting mechanism.

glm approach uses same data , uses union alias mechanic.

your approach might 'better' c++ worse 'engineering'. vector math needs fast, , smaller better in case.

your implementation makes vector 3 times bigger. sizeof(glm::vec4); // 16 while sizeof(your_vec4); // 48 - ouch if processing large armount of these case, 3 times more cache misses your_vec4.

i think right though glm's use of unions alias's bit much, while i'm not sure if undefined, type of thing i've seen lot without issue, , glm used.

i don't see need emulate glsl in c++, , struct { float x,y,z,w; } better (at least in mind).


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -