Possible way to achieve lazy loading with const objects

Jonathan M Davis jmdavisProg at gmx.com
Sun Sep 25 17:19:29 PDT 2011


On Monday, September 26, 2011 02:03:23 Simen Kjaeraas wrote:
> On Mon, 26 Sep 2011 02:02:06 +0200, Simen Kjaeraas
> 
> <simen.kjaras at gmail.com> wrote:
> > On Sat, 24 Sep 2011 13:19:33 +0200, Peter Alexander
> > 
> > <peter.alexander.au at gmail.com> wrote:
> >> Lazy loading and caching are the same thing.
> >> 
> >> struct Foo
> >> {
> >> 
> >>      T m_lazyObj = null;
> >>      bool m_isLoaded = false;
> >>      
> >>      T getObj()
> >>      {
> >>      
> >>          if (!m_isLoaded)
> >>          {
> >>          
> >>              m_lazyObj = func();
> >>              m_isLoaded = true;
> >>          
> >>          }
> >>          return m_lazyObj;
> >>      
> >>      }
> >> 
> >> }
> >> 
> >> Change m_lazyObj to m_cachedObj and m_isLoaded to m_isCached and you
> >> have caching.
> > 
> > This is too simple. If the system also rewrites all members to
> > @properties that
> > sets m_isLoaded = true, it might work. Example:
> > 
> > struct S {
> > 
> >      int n;
> >      lazy int otherN = () { return n + 2; } // compile time error
> >      here
> > 
> > if you refer to lazily initialized members.
> > }
> > 
> > =>
> > 
> > struct S {
> > 
> >      int __n;
> >      int __otherN;
> >      bool __otherNloaded = false;
> >      
> >      
> >      @property
> >      int n( ) {
> >      
> >          return __n;
> >      
> >      }
> >      
> >      @property
> >      int n(int value) {
> >      
> >          if (__n != value) {
> >          
> >              __n = value;
> >              __otherNloaded = false;
> >          
> >          }
> >          return __n;
> >      
> >      }
> >      
> >      @property
> >      int otherN( ) {
> >      
> >         if (!__otherNloaded) {
> >         
> >             __otherN = () { return n + 2; }();
> >             __otherNloaded = true;
> >         
> >         }
> >         return __otherN;
> >      
> >      }
> > 
> > }
> > 
> > Now, the overhead might be troublesome, but this seems to me to work.
> 
> Oh, and of course more stuff is need if you try to make this work across
> threads.


The threading issue is exactly why I suggested that objects which are 
constructed as shared automatically have the property called at the end of the 
constructor (to force initialization) and that an opCast to shared should be 
added which does the same (or if there's already one, then the call to the 
property function is added at the end of it). You should completely eliminate 
the threading issues that way.

- Jonathan M Davis


More information about the Digitalmars-d mailing list