Best practices of using const

Yatheendra 3df4 at gmail.ru
Sat Jun 22 08:02:42 UTC 2019


On Saturday, 22 June 2019 at 05:10:14 UTC, Yatheendra wrote:
> It feels disingenous to want to call a caching object even 
> "logically" const. There has to be a scaffolding-based but 
> hopefully generic compromise. I haven't yet tested this belief, 
> but I believe "physical" const is of good use wherever it can 
> be applied.
>
> On Friday, 21 June 2019 at 23:39:20 UTC, H. S. Teoh wrote:
>> The problem with this is that you cannot use const(Wrapper).
>>
>> In particular, if you have a function that wants to document 
>> that it does not mutate its argument, you cannot write:
>>
>> 	auto func(in Wrapper data) { ... }
>>
>> because const(Wrapper) does not allow lazy initialization.
>> ...
> ...

"physical" const has to be applicable & good in many/most other 
use-cases than caching (citation needed). Somehow, wanting to 
call mutating code on logically const values sounds to be the 
wrong want.

Lazy initialization sounds like it will be a good DIP :-) 
Generate (once) on (first) read, just like copy (once) on (first) 
write. But there are other ways.

Heavy computation called at most once: bite the bullet, eagerly 
construct an immutable value ahead of time. "physical" const 
might have just enough optimization opportunity to offset biting 
the bullet.

Called more than once: same thing.


More information about the Digitalmars-d-learn mailing list