Re:Optimizing C++ Const Objects in LLVM
by MereInterest on Sunday December 27, 2015 @01:06PM
(#10798196)
When reading from a binary source, I've seen that, instead of unions, the char pointer will be cast to a pointer to the appropriate data structure. What is the advantage of using a union instead of casting?
[ Parent
| on HN ]
Re:Optimizing C++ Const Objects in LLVM
by theseoafs on Sunday December 27, 2015 @01:20PM
(#10798234)
Well, for one, unions have defined behavior in C, while passing pointers around and casting them randomly doesn't.
I don't know if this is the best example. Generally you see unions in C to cover "tagged unions", I.e. Those things that would be subsumed by algebraic data types in other languages.
Re:Optimizing C++ Const Objects in LLVM
by MereInterest on Sunday December 27, 2015 @07:48PM
(#10799293)
Ah, got it. I am used to C++, where accessing the non-active member of the union is undefined behavior. Thank you.
Re:Optimizing C++ Const Objects in LLVM
by stephencanon on Sunday December 27, 2015 @07:23PM
(#10799239)
The usual way to do this via memcpy, rather than either a union (requires some non-portable extension like "packed") or pointer casting (invokes undefined behavior if alignment isn't satisfied).