On Sunday, 15 November 2015 at 18:26:56 UTC, Ola Fosheim Grøstad wrote:
On Sunday, 15 November 2015 at 15:14:38 UTC, Jonathan M Davis wrote:
mutating is undefined behavior, arguing that if it weren't, it would be like C++'s const and that C++'s const is pretty much useless, because it doesn't provide actual guarantees.

Hm, I think C++ const requires that the object isn't modified, but you can cast away const in order to call functions that are erroneously missing a const specifier.

C++'s solution is to have a "mutable" specifier for fields like that can be mutated without affecting the type's state externally (mutexes etc).

From the C++ faq:

«NOTE: there is an extremely unlikely error that can occur with const_cast. It only happens when three very rare things are combined at the same time: a data member that ought to be mutable (such as is discussed above), a compiler that doesn’t support the mutable keyword and/or a programmer who doesn’t use it, and an object that was originally defined to be const (as opposed to a normal, non-const object that is pointed to by a pointer-to-const). Although this combination is so rare that it may never happen to you, if it ever did happen, the code may not work (the Standard says the behavior is undefined).»

So const_casting away const followed by mutation is undefined behaviour.

As I understand it, the only time that casting away const and mutating is undefined behavior in C++ is when the object was specifically constructed as const such that no mutable reference to it even can exist without a cast - which would be the bit from that quote where it talks about "an object that was originally defined to be const". And in general, _very_ few objects are likely to be constructed as const. So, in general, in C++, you can cast away const and mutate as much as you'd like. It's just that that's generally considered bad practice, and folks usually behave themselves and try to use const as a "logical" const such that no member variables which would normally be considered part of the state of the object have a different value after a const function call than what they had before the function call. So, for the most part, const works by convention.

- Jonathan M Davis

Reply via email to