preparing for const, final, and invariant

Aarti_pl aarti at interia.pl
Fri May 18 01:47:02 PDT 2007


Walter Bright pisze:
> This is coming for the D 2.0 beta, and it will need some source code 
> changes. Specifically, for function parameters that are arrays or 
> pointers, start using 'in' for them.
> 
> 'in' will mean 'scope const final', which means:
> 
> final - the parameter will not be reassigned within the function
> const - the function will not attempt to change the contents of what is 
> referred to
> scope - the function will not keep a reference to the parameter's data 
> that will persist beyond the scope of the function
> 
> For example:
> 
> int[] g;
> 
> void foo(in int[] a)
> {
>     a = [1,2];    // error, a is final
>     a[1] = 2;   // error, a is const
>     g = a;    // error, a is scope
> }
> 
> Do not use 'in' if you wish to do any of these operations on a 
> parameter. Using 'in' has no useful effect on D 1.0 code, so it'll be 
> backwards compatible.
> 
> Adding in all those 'in's is tedious, as I'm finding out :-(, but I 
> think the results will be worth the effort.

I want to ask about something opposite to above example...

Will it be possible to pass ownership of object? I mean that when you
pass object by reference to function/class/member variable you can still
modify this object from outside of function/class. It breaks
encapsulation in program.

Example:

import std.stdio;
public class TestX {
    char[] value;
    char[] toString() {
        return value;
    }
}
public class TestMain {
    TestX x;
}

void main(char[][] args) {
       TestX parameter = new TestX();
       parameter.value = "First assignment";

       TestMain tmain = new TestMain();
       tmain.x = parameter;

       parameter.value = "Second assignment";
       writefln(tmain.x);
}

Notice that tmain.x value has changed although I would like just to set
once, and have second assignment to parameter illegal... When using
setters and getters problem is even more visible....

How to achieve proper behavior with new final/const/invariant/scope??

Regards
Marcin Kuszczak
(aarti_pl)



More information about the Digitalmars-d-announce mailing list