Possible way to achieve lazy loading with const objects

Martin Nowak dawg at dawgfoto.de
Wed Sep 28 13:02:23 PDT 2011


On Wed, 28 Sep 2011 21:58:20 +0200, Martin Nowak <dawg at dawgfoto.de> wrote:

> On Wed, 28 Sep 2011 18:00:39 +0200, Steven Schveighoffer  
> <schveiguy at yahoo.com> wrote:
>
>> On Wed, 28 Sep 2011 11:55:01 -0400, Kagamin <spam at here.lot> wrote:
>>
>>> Steven Schveighoffer Wrote:
>>>
>>>> Trivial, and also undefined behavior ;)
>>>
>>> Well, it gets job done. If you don't like it, don't use logical const.
>>
>> It's not a matter of whether I don't like it or not.  Undefined  
>> behavior means anything can happen.  The application could crash.   
>> Memory could become corrupted.
>>
>> I feel like in this area, labelling this as "undefined behavior" is an  
>> extreme.  I think with the right implementation (and the right  
>> preconditions), it should be possible to safely cast away const and  
>> modify the data.
>>
>> I think it's worth trying to do.  All I was saying is, the language is  
>> not going to help you out on that.
>>
>> -Steve
>
> Const is the union of mutable/immutable, both can be implicitly  
> converted to const.
> This means one can't distinguish ROM data from mutable data based on  
> having const.
> Because immutable data is convertible to const, const is a promise not
> to change the data (while immutable is the promise that the data won't  
> change).
> Actually if one thinks of const declarations as immutable data being  
> implicitly converted to const,
> then there is only mutable or immutable data, with const being the  
> polymorph container.
>
> Now an issue arises when the programmer choses to only use the mutable  
> subset to avoid accidental changes.
...to wrap mutable data with const to avoid accidental changes.

> The logical const idiom is used to do a reasonable change of data.
> This conflicts with the language providing const to hold mutable and  
> immutable data.
>
> What is needed here is a construct that can hold only mutable data.
>
> A simple lvalue wrapper solves most of the problem.
> It provides the necessary safety and adds an explicit, safe hole
> to do changes.
>
> struct Mutable(T) if(!is(T == const) && !is(T == immutable))
> {
>      // enforce construction with mutable value at runtime
>      this(T t) { if (__ctfe) assert(0); _t = t; }
>
>      // default access same as own qualifier
>      @property ref T get() { return _t; }
>      @property ref const(T) get() const { return _t; }
>      @property ref immutable(T) get() immutable { return _t; }
>      alias get this;
>
>      // privileged access through explicit/self-documenting method
>      @property ref T rvalue() const { return *cast(T*)&_t; }
>
> private:
>      // mutable value
>      T _t;
> }
>
> What would be nice from the language side is allowing to write '@disable  
> this() immutable'.
>
> martin


More information about the Digitalmars-d mailing list