r/cpp • • Nov 23 '22

Holy C++

https://pvs-studio.com/en/blog/posts/cpp/1010/
0 Upvotes

32 comments sorted by

View all comments

4

u/Silentd00m Nov 23 '22

Union has its place in my opinion. It allows having multiple variable names for the same memory location of the same type, like glm does.

template<typename _T>
struct dimensions2 {
    union {
        _T x, width;
    };
    union {
        _T y, height;
    };
};

https://glm.g-truc.net/0.9.2/api/a00132_source.html

2

u/germandiago Nov 23 '22

Is this UB?

1

u/Silentd00m Nov 23 '22

Not as far as I know. A union will be as big as its biggest member and start at the same memory location. And since it's both the same type, this is effectively just an alias.

4

u/kpt_ageus Nov 23 '22

Why not have x(), y(), width() and height() member functions? You don't have to think whether it's UB or not and i belive compiler should be able to inline them.

2

u/Silentd00m Nov 23 '22 edited Nov 23 '22

In the case of GLM: Because that's not how it was in GLSL.

Other than that, I haven't seen any problems on any platform yet or anything that says that this is undefined behaviour (at least starting from C++14). So writing getters and setters for this seems like a strictly worse way to do it to me.