On Friday, August 17, 2012 03:51:36 Mehrdad wrote: > On Friday, 17 August 2012 at 01:33:29 UTC, Chris Cain wrote: > > Also, if the only view of the data you have is that const view, > > it's effectively the same as immutable (it couldn't be changed > > by any valid code). > > So you're saying casting away a const _pointer_ is undefined, > even if the target was originally created as mutable. (Otherwise, > the code would certainly be "valid", just like in C++.) > > > Which means you can effectively _never_ cast away constness of a > pointer/reference, no matter how certain you are about the target > object, right? > > If you did, then the code would be invalid, and the compiler > could simply format your C: drive instead of modifying the object. > > If so, then why is such an undefined cast allowed in the first > place?
Because there are plenty of functions which take mutable objects but don't actually alter them - particularly when interacting with C code. It's the sort of thing that you really shouldn't be doing normally but on rare occasions is useful - in this case when dealing with code that isn't const correct but still won't actually alter the object. - Jonathan M Davis