Possible way to achieve lazy loading with const objects

Jonathan M Davis jmdavisProg at gmx.com
Mon Sep 26 09:22:10 PDT 2011


On Monday, September 26, 2011 10:35:29 Steven Schveighoffer wrote:
> On Mon, 26 Sep 2011 09:44:31 -0400, Regan Heath <regan at netmail.co.nz>
> 
> wrote:
> > On Mon, 26 Sep 2011 13:01:29 +0100, Steven Schveighoffer
> > 
> > <schveiguy at yahoo.com> wrote:
> >> On Sat, 24 Sep 2011 00:11:52 -0400, Jonathan M Davis
> >> 
> >>> 6.  If the S being constructed is shared or immutable and __varProp
> >>> is
> >>> not
> >>> called in the constructor, then __varProp is called immediately
> >>> after
> >>> the
> >>> constructor (or at the end of the constructor if that works better
> >>> for
> >>> the
> >>> compiler).
> >> 
> >> Why?  What if the calculation is very expensive, and you never access
> >> var?
> >> 
> >> Besides, we can already pro-actively initialize data in an immutable
> >> constructor, what is the benefit here?
> > 
> > I think this is to avoid threading issues, like double checked locking
> > problems etc.
> 
> My point is, can't I do this now?
> 
> struct S
> {
>     int var;
>     immtuable this() { var = func(); }
>     const int func() {...}
> }
> 
> vs
> 
> struct S
> {
>     lazy int var = func();
>     const int func() {...}
> }
> 
> If you aren't going to *actually* lazily initialize a variable, what is
> the point of all this?  I can non-lazily initialize a variable without any
> new language features.

The point was to allow for lazy initialization when _not_ using immutable or 
shared but to still have the type work when immutable or shared. If lazy 
loading were implemented as I suggested but made no attempt at dealing with 
immutable, then it would have to be _illegal_ to use such a type with 
immutable, because lazily loading the member variable would violate 
immutability. Allowing it would potentially result in trying to alter read-
only memory.

By forcing eager loading with immutable and shared, you avoid the immutability 
and threading problems but still allow lazy loading with const. The whole 
point of this proposal is to allow for lazy loading and const to mix. If all 
you want is lazy loading, then you can do it right now, but you can't do it 
with const. But since lazy loading and immutable don't mix at all and _can't_ 
(since immutable objects could be put in read-only memory), you either have to 
make immutable illegal with such objects or make them eagerly load for 
immutable.

- Jonathan M Davis


More information about the Digitalmars-d mailing list