Possible way to achieve lazy loading with const objects
Simen Kjaeraas
simen.kjaras at gmail.com
Sun Sep 25 17:03:23 PDT 2011
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.
--
Simen
More information about the Digitalmars-d
mailing list