3 ms·
> You can cast T to const T, but not vice versa. Humm, actually, you can. But guess what ? Modification of the underlying data is an UB !
by _ache_ 4y ago
> You can cast T to const T, but not vice versa.
Humm, actually, you can. But guess what ? Modification of the underlying data is an UB !
- pif 4y agoWhich is the only possible logical consequence of modifying something that others asked you not. const_cast is there for buggy (or legacy) libraries where const was not specified explicitly, but is implicit in the behavior.
- _ache_ 4y agoIt can happen easily if you don't pay attention with only the standard library. const char *hello = "Hello World !", *world = "World"; char *tmpStr = strstr(hello, world); // IMPLICITE cast from const to non const if(tmpStr) { *tmpStr = 0; // Oupss } C is hard.
- synergy20 4y agoso how to safely use strstr then? this is truly a bug hard to find, yet another caveat. not sure if fuzz testing can help here. I wonder how many implicit-const-to-non-cost API are in ANSI C and Posix C
- LegionMammal978 4y agoIt's only UB if the original variable is declared with a const type. If you convert a modifiable T * into a const T *, then cast it back into a T *, then you can modify it without any issues.