#Allocate one variant of `union`
1 messages · Page 1 of 1 (latest)
Yes you can allocate a B but it will be a different length in memory and defeats any benefit you would get from a union, so it depends on your use case
Casting it however will probably not work or be any more efficient
In this case, I would consider avoiding a builtin union, as---IIRC---they have no defined layout.
Ideally, it would be nice if there was a way to do this with the builtin union perhaps, but there isn't currently.
An alternative impl is that you use the "encoding" pattern.
Andrew explains it here (https://vimeo.com/649009599) at the 23:25 mark.
Andrew Kelley, creator of Zig, picks up where Mike Acton left off to teach us practical ways to apply data-oriented design References: - CppCon 2014: Mike Acton…
What would it even mean to do this? At best you can say the part of the union you don't need is uninitialised memory, which is what memory allocating gives you anyway
I think the best way to achieve this would be to allocate A and B instead of allocating C:
So const C = union {a: *A, b: *B}
This is certainly worthy of consideration, yeah.
This way each union is only 16 bytes, tops.
thanks for the input
I'd be cautious if you were to do this
Make sure the allocation is also aligned to the smaller of the two, as opposed to being aligned to the larger of the two, lest you risk loading garbage memory from an over-aligned memory location or register
(and if you do do it, use extern union)
I think this won't be an issue if I use the "union of pointers" approach? That'd allow me to allocate the correct struct.
yeah, no issue there