Lazily Initialized Variables that are Compatible with const/immutable
MorteFeuille123
MorteFeuille123 at mrt.rt
Thu Nov 17 12:04:43 UTC 2022
On Thursday, 17 November 2022 at 10:57:55 UTC, Vijay Nayar wrote:
> An uncommon, but not rare, situation that I run into from time
> to time, is that there are variables used either globally or as
> a member of a class that are expensive in their resource usage
> (time to compute, or memory size), but which are only sometimes
> used, e.g. only when certain functions are called, which
> depends on the runtime usage of the program.
>
> The concept of [lazy
> initialization](https://en.wikipedia.org/wiki/Lazy_initialization) is used in these situations to avoid paying this cost up front, and deferring it until the value is used. E.g. if your object has a member named `value`, then `obj.value` may refer to a method that returns a cached value, and if the cache is empty, produces the value and caches it.
>
> However, in D, such usage runs into problems when the
> object/method is either `const` or `immutable`. Making such
> changes requires modifying a variable that technically existed
> at the time `obj` was created.
>
> [...]
>
> Is there another way to perform lazy initialization that is
> compatible with const/immutable, or is this needed as a
> language feature?
No, this is needed as a bultin feature I'd say. I sometime think
that since we can have local static variablbes, we could have
local member variables. Similarly hiddden, only accessible
through a getter, which replaces the need for a const member.
More information about the Digitalmars-d
mailing list