Best practices for logical const

Jonathan M Davis jmdavisProg at gmx.com
Sat Feb 15 22:28:16 PST 2014


On Sunday, February 16, 2014 03:25:08 Stanislav Blinov wrote:
> On Saturday, 15 February 2014 at 04:03:51 UTC, Adam D. Ruppe
> wrote:
> 
> What about a library solution for something like C++-esque
> mutable?

You're casting away const if you do that, and that's precisely what you 
shouldn't be doing. const is for _physical_ constness and should never be used 
if you want logical constness. Even attempting to use const for logical 
constness is incredibly dangerous, and the compiler is free to change what it 
does based on the knowledge that an object cannot be changed via a const 
reference and that an immutable object can never be changed. So, even if you 
manage to get away with casting away const and mutating in a particular 
situation right now, there's no guarantee that that code will work across 
compilers or architectures or that it will continue to work on future versions 
of the same compiler. The best thing to do is to just forget about even 
attempting to use const for logical constness. That's not what it's for, and 
you're going to have bugs (potentially very nasty and subtle bugs) if you 
attempt it.

- Jonathan M Davis


More information about the Digitalmars-d mailing list