3 ms·
Arguably, C++ arguably already solved that specific problem with const safety. I was flabbergasted back in 1995 that Java had dropped that notion.
by layer8 3y ago
Arguably, C++ arguably already solved that specific problem with const safety. I was flabbergasted back in 1995 that Java had dropped that notion.
- kevincox 3y agoI don't think it does. In C++ taking a const argument just means that you can't change it. But since the caller can pass non-const as const there is nothing stopping them from mutating it.
- Zach_the_Lizard 3y agoYou can also use const_cast to remove the const-ness. You could then mutate the value. I believe that's undefined behavior territory (the mutation, at least in most cases), but I'm sure someone is doing it in the wild.
- kevincox 3y agoI haven't done much C++ in a few years but IIRC you can remove const as long as the "original" value isn't const. So `const_cast((*const Foo)foo)` is fine if foo is not const.
- erik_seaberg 3y agoIsn’t the linker entitled to put a constant object in a read-only page of the binary if it doesn’t require a ctor at runtime?
- kevincox 3y agoYes. That is why global static `const`s (with exceptions like if they have mutable fields) can't legally have their `const` casted away.
- taejo 3y agoIf the constructor here would take a const reference, it would have the same problem (the existence of a const reference doesn't preclude non-const references to the same object). If it took an argument by value, it wouldn't make a difference whether it was const or not, because no other thread could have access to the same object, because it would be copied. In Rust, on the other hand, if there's a mutable reference to an object, there can be no other references to the same object at the same time.