Best practices for logical const

Jonathan M Davis jmdavisProg at gmx.com
Sat Feb 15 02:52:08 PST 2014


On Saturday, February 15, 2014 04:03:50 Adam D. Ruppe wrote:
> D doesn't have logical const, but sometimes it is useful,
> especially with lazy initialization of a field, and we can kinda
> fake it with casts or with global variables. Modifying an
> immutable object is undefined behavior, so how can we avoid that,
> and if not, try to minimize the problems in practice?
> 
> Using global variables to store local state is kinda silly, it
> seems to me that doing a AA lookup kinda defeats the point of
> caching in the first place, so I want to focus on the cast method.
> 
> So:
> 
> * should we always wrap the write in a synchronized block to
> minimize the chances that we'll have thread problems with
> implicitly shared immutable things passed as const? What's the
> best way to do this btw?
> 
> * should objects with logical const methods deliberately not
> provide immutable constructors to prevent them from being
> immutable? Would this actually work?
> 
> * Anything else that is likely to come up?

If you want logical const, don't use const or immutable at all. To do so is 
undefined as they require physical constness/immutability. So, if you want 
logical const, you need to indicate constness in some other way that's not 
defined by the language. Pretty much by definition, you can't have logical 
const with const or immutable, because the only way to even attempt it 
involves casts, which means undefined behavior. I'd strongly advise against 
even considering it, let alone trying it.

- Jonathan M Davis


More information about the Digitalmars-d mailing list