mutable constant?

monarch_dodra monarchdodra at gmail.com
Wed Jun 26 04:16:16 PDT 2013


On Wednesday, 26 June 2013 at 07:35:08 UTC, Namespace wrote:
> On Tuesday, 25 June 2013 at 23:39:45 UTC, Ali Çehreli wrote:
>> With apologies, I have unrelated comments to make.
>>
>> On 06/25/2013 03:07 PM, Namespace wrote:
>>
>> >     this(T x, T y) {
>> >         this.x = x;
>> >         this.y = y;
>> >
>> >         points ~= &this._point;
>>
>> I have seen similar designs in the past where constructors had 
>> side-effects such as registering the object in a global state. 
>> (Exactly what the last line is doing above.)
>>
>> It has almost always been cause of trouble. It is better to 
>> register an object from the outside after constructing it.
>>
>> Sometimes I had attempted to remove seemingly unused objects 
>> only to be reminded by a comment that it should not be:
>>
>>    // Do not remove! Registers itself in the points array
>>    auto p = Point();
>>
>> >     @property
>> >     inout(Point)* ptr() inout {
>> >         points[this.id].x = cast(int) this.x;
>> >         points[this.id].y = cast(int) this.y;
>>
>> That looks questionable as well: ptr() looks like an accessor 
>> but it makes changes to a global state.
>>
>> Ali
>
> This is no real code. Just a test example to check. ;)

It seems safe, however, your example seems to show how to indeed 
break the type system... without a cast (!):

     @property
     Point* ptr() inout {
         points[this.id].x = cast(int) this.x;
         points[this.id].y = cast(int) this.y;

         return points[this.id];
     }


void main() {
     immutable TplPoint!float my = TplPoint!float(42, 23);
     Point* p = my.ptr; //Oops! mutable point!
}

Disturbing...

>     this(T x, T y) {
>         this.x = x;
>         this.y = y;
>
>         points ~= &this._point;

I'd careful with this, you can easily end up with pointers to 
destroyed temporaries...


More information about the Digitalmars-d-learn mailing list