4 ms·
I guess I had the benefit of some years of learning to smell for C aliasing violations, but even if I hadn't, static_cast would have been a dreadful way to lear
by gok 7y ago
I guess I had the benefit of some years of learning to smell for C aliasing violations, but even if I hadn't, static_cast would have been a dreadful way to learn. If static_cast were purely to detect pointer aliasing violations, it may have some amount of usefulness. But it also whines on totally legitimate conversions. Like both these casts:
// float *x = ...
static_cast<int*>(x)
static_cast<intptr_t>(x)
…give the exact same compiler error. And in the case of the first one, which is actually bad, the compiler can't explain why it's dangerous. Thus it doesn't actually tell me "hey you probably are casting to the wrong thing", but rather "you picked the wrong cast to make the compiler happy".
- ycombobreaker 7y agoThe static_cast vs. reinterpret_cast is also executable documentation for your readers. Sounds like you have a strong handle on this, and it's a free opportunity to make your future maintainers' lives a little bit easier.
- gok 7y agoI appreciate that in general but not here. What does reinterpret_cast<intptr_t>(p) tell a reader that (intptr_t)p doesn't?
- ycombobreaker 7y agoSince this is about maintenance, it's ultimately craftsmanship (IMHO) amd I don't think I can give a great answer without knowing real context. Here's one possibility that comes to mind: Places where I would _expect_ to see something like this are C APIs where void pointers are used to provide "userdata context", such as pthread_create. Using the reinterpret-cast-to-pointer-sized-thingie(void* or intptr_t or uintptr_t) makes it clear that we're discarding all type safety and probably doing something similar. The C style cast does not express that as clearly. Is the impact substantial? Not really. But in maintenance of long lived code bases, small impacts accumulate.