Extended Type Design: further examples

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Tue Mar 20 21:31:46 PDT 2007


jovo wrote:
> Andrei Alexandrescu (See Website For Email) Wrote:
> 
>> (Reposted after cleanup :o))
>>
>> kris wrote:
>>> How about some further example? Given these sigs:
>>>
>>> struct Foo
>>> {
>>>    int a;
>>> }
>>>
>>> class Bar
>>> {
>>>    char[] b;
>>> }
>>>
>>> void fooish (inout Foo foo) {}
>>>
>>> char[] barish (Bar bar) {return bar.b;}
>>>
>>>
>>> 1) how do I modify the function decls to have the compiler *enforce* 
>>> readonly upon the referenced content? e.g. Foo.a and Bar.b cannot be 
>>> mutated within the function body?
>> void fooish (const ref Foo foo) {}
>>
> 
> 
> void fooish(const ref Foo foo) {
>     foo.a = 1;                   // not allowed

Not allowed indeed.

>     foo = sam_Foo;           // allowed?

Not allowed. The type of foo is const(ref(Foo)). When you try to assign 
to foo, you'll assign to indirectly referenced bits. If you only replace 
Foo with int (which makes sense because Foo is a struct), you'll see how 
trying to assign the int would indirectly modify memory outside the 
function.

Now consider:

void Fun(ref const Foo foo) {
}

The type of foo is ref(const(Foo)). So the function has a reference to a 
constant object. It can modify the direct fields of the object, but 
nothing beyond that. It's not a very useful case. We might even choose 
to prohibit it statically unless compelling use cases show up. I 
actually already think of a couple :o).


Andrei



More information about the Digitalmars-d mailing list