| ▲ | arcticbull 2 hours ago | |
Yeah but also, quick question:
If you answered 0, you'd be wrong, the answer is undefined, thanks to padding, initialization and alignment rules. Padding bytes are undefined, and not guaranteed to be initialized to zero even if the variable is declared static (where the members would be zeroed).This is why the compiler is angry at the post writer, and why the reinterpret_cast is needed. Ideally if they wanted to do something with the data, they'd unbox the structure. That's why it's not a good idea to use void* to pass arbitrary data interchangeable with bytes. It's a location, it makes no representation as to what's there and how to interact with it. Let alone who owns it. std::span solves two problems here. One is the ownership problem. The other is that span<T> is a T[]. void* is god only knows. The post asserts: > The code is very clear and straightforward: you pass a pointer to the custom data structure, and its size in bytes. That’s it. Simple and clear. This is unfortunately entirely false in C thanks to the aforementioned alignment/padding UB (and of course inner pointers). This is addressed with std::span. You'd still have to reinterpret_cast your structure to get the UB. > Why should people complexify and uglify their C++ code with the uint8_t pointer (or std::byte), when void* works just fine?? tl;dr: because it doesn't. It just kinda looks like it does if you squint, and it's going to lead to the gnarliest bugs in the world. | ||
| ▲ | saagarjha 41 minutes ago | parent | next [-] | |
Padding bytes are initialized to zero if you zero initialize the aggregate. It is hard to keep those bytes as zero but at initialization this much is guaranteed. | ||
| ▲ | porridgeraisin an hour ago | parent | prev [-] | |
> even if the variable is declared static No, for static even padding bytes are zero. For automatic, yes it may effectively turn a = {} to a.member = 0, leaving the padding bytes uninitialised. Or on copies like a = b it may not copy padding bytes. | ||