3 ms·
Const-correctness doesn't actually work in C++. It's more of a documentation aid. (It doesn't work because it can be cast away. It's also not transitive, so is
by WalterBright 4y ago
Const-correctness doesn't actually work in C++. It's more of a documentation aid.
(It doesn't work because it can be cast away. It's also not transitive, so is ineffective with generic template code.)
D code won't allow const to be cast away (unless in system code), and is transitive. Sometimes people complain that this is too harsh, but it's reliable and effective.
- maccard 4y agoI 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