3 ms·
I can't believe I'm about to try and correct you of all people on this but you can't just const_cast away[0]. The actual problem is that you have no guarantee t
by maccard 4y ago
I can't believe I'm about to try and correct you of all people on this but you can't just const_cast away[0]. The actual problem is that you have no guarantee that what you're being told is const is actually const. If you have a const ref to an object, that doesn't mean it's actually initialised as const, for example.
[0] well of course technically you can, but casting a CV qualifier away and modifying it is UB.
- WalterBright 4y agoYes, you are correct, it is UB. Try this code: void foo(const int * const p) { *(int*)p = 3; // UB? So sue me! } It compiles with g++ and clang++ with no warnings or errors. gcc and clang, too. Sure, it's UB, but the compiler won't even warn you. I.e. it serves no purpose, other than documentation. Let's try it in D: @safe void foo(const int *p) { *cast(int*)p = 3; } Error: cast from const(int*) to int* not allowed in safe code
- maccard 4y agoI think we're in agreement here, but speaking past each other! Your snippet isn't actually UB though, it's perfectly fine. See [0] > I.e. it serves no purpose, other than documentation Yeah, agreed. [0] https://gcc.godbolt.org/z/v4qYME8fP https://gcc.godbolt.org/z/v4qYME8fP