Possible way to achieve lazy loading with const objects

Jonathan M Davis jmdavisProg at gmx.com
Sat Sep 24 04:47:49 PDT 2011


On Saturday, September 24, 2011 12:19:33 Peter Alexander wrote:
> Lazy loading and caching are the same thing.

No. Caching is more general. Lazy loading is explicitly one load and has 
different characteristics, whereas is caching can have multiple loads.

> 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.
> 
> A problem with your suggestion is that it can only handle one load. It's
> very often the case that you need to mark the object as 'dirty' and set
> the flag back to false so that it gets reloaded.

The problem with this is that with a single load, you can guarantee constness, 
but once you have multiple, you can't. Unless you can find a mechism which 
_guarantees_ logical constness while changing the variable multiple times, 
then you can't guarantee constness, and it doesn't work. Also, whatever the 
mechanism is, it _has_ to work in the face of immutable, which may or may not 
be harder with a more general caching mechanism.

This particular solution jsn't even _trying_ to solve the caching problem. I 
seriously question that that's at all solvable without breaking const. The 
whole reason that this could work is because it does the load only once, which 
therefore guarantees that the value never changes and therefore never breaks 
const. This is only attempting to solve the lazy-loading issue, not the 
general caching issue.

If you can come up with a way to do general caching without breaking const, 
then that's great. But all I've been able to come up with is a potential means 
of doing lazy loading.

But really, my real question here is whether this scheme is really feasible or 
whether I've missed something. If it's feasible, then _maybe_ it's possible to 
build on it somehow to come up with a general caching mechanism (though I 
doubt it), but if it's _not_, then obviously this sort of approach isn't going 
to be able to do a single lazy load, let alone be expanded somehow to make 
general caching possible.

- Jonathan M Davis


More information about the Digitalmars-d mailing list