3 ms·
What is the argument in favor of specifically allowing casting away const of pointers?
by btrask 10y ago
What is the argument in favor of specifically allowing casting away const of pointers?
- ridiculous_fish 10y agoThe strongest argument is to support a sort of poor man's const-generics. Consider a function like strchr(). This locates a character in a (const) string, and returns a (non-const) pointer to it. The idea is that you can use this on both const and non-const strings. Call it on a const string, you get back a non-const pointer (which you better treat as const!) But call it on a non-const string, you get back a non-const pointer, with which you can mutate the string. So a single function serves both const and non-const uses. If casting away const-ness were disallowed, the compiler might conclude that strchr()'s returned value cannot alias the input string, and its optimizations would defeat this design. Anyways that's the original rationale.
- mannykannot 10y agoIt does not strike me as much of a benefit, and certainly not worth the cost of creating confusing semantics (in fact, I would prefer (a true) const to be the default in any language, with something like 'mutable' required to override.)
- nialv7 10y agoAnd that's why D has the 'inout' qualifier
- WalterBright 10y agoLogical const and expressiveness.
- Rexxar 10y ago- In some case implementing both "const" and "non const" methods cause a lot of code duplications and cast can help. - Compatibility with old libraries
- WalterBright 10y ago> implementing both "const" and "non const" methods cause a lot of code duplications D has an `inout` qualifier that has the effect of "transmitting" the const-ness of an argument to the return type.