What guarantees does D 'const' provide, compared to C++?

Jonathan M Davis jmdavisProg at gmx.com
Thu Aug 16 19:14:16 PDT 2012


On Friday, August 17, 2012 03:59:01 Chris Cain wrote:
> If you're absolutely 100% completely totally certain that the
> data is mutable (i.e., you have confirmed either through good,
> sound reasoning OR you have some method of seeing exactly where
> it is stored in your RAM and you've checked that the place it is
> stored is writable memory), then __technically__, yes you can
> cast away and modify away. Apparently, according to some, it's
> necessary for low level programming. I'd highly discourage this
> type of behavior because if you're doing something like that I'm
> nearly certain you could come up with a better design, not to
> mention you're missing the point of having something const in the
> first place.

It's still technically undefined behavior. It's just that there's pretty much 
no way that the compiler is going to be written in a way that it won't work. 
However, you _do_ still risk running into problems because the compiler may 
make optimizations that you're violating by modifying the object. So, even if 
you're _certain_ that the object is actually mutable and you're _certain_ that 
nothing will blow up when you cast away const and modify it, you _still_ could 
get bugs due to compiler optimizations.

- Jonathan M Davis


More information about the Digitalmars-d mailing list