Difference betwee storage class and type (invariant/const)?

Robert Fraser fraserofthenight at gmail.com
Wed Jun 20 15:15:52 PDT 2007


Yup, that sort of makes sense, thanks.

Now I'm just wierded out by the whole thing where struct members can change value but things pointed to by the struct members can't. But I'll get used to it eventually. I think for the time being, I'll just put "in" on all my method signatures, remove it when the compiler complains, and not worry about the rest.

Daniel Keep Wrote:

> 
> 
> Robert Fraser wrote:
> > Christian Kamm Wrote:
> > 
> > [...]
> > 
> >> struct S { int x; int* p; }
> >> invariant(S) bar;
> >> bar.x = 1; // ok
> >> *bar.p = 1; // fails: not mutable
> > 
> > Wait, so non-reference-types are mutable, but the data pointed to by reference types isn't...? Hwah...? I understand that structs are value types, but does this mean that the values within the struct can be changed while the values the struct points to can't be? And this differs from a class because a class is a reference type by default...?
> > 
> > So, wait,
> > struct Foo { int x; }
> > class Bar { int x; }
> > const(Foo) foo;
> > const(Bar) bar = new Bar();
> > foo.x = 5; // Ok...?
> > bar.x = 5; // Compile-time error...?
> > 
> > Weird. I've always just used structs as stack-allocated classes without inheritence, constructors, or the overhead. Now there's another difference to worry about, I guess because they're value types...
> > 
> >> static if(is(invariant(S*) == invariant(S)*))
> >> does not pass, but
> >> invariant(S*) barptr2 = &bar;
> >> static if(is(typeof(barptr2) == invariant(S)*))
> >> passes... is there a logical explanation for that?
> > 
> > Now I'm even more confused... I'm from a Java background, so I don't really understand constness already, and the implementation here seems to be way weird...
> > 
> > Anyways, thanks all...
> > I guess I'll wait until the implementation matches the docs and there's a tutorial or something out there which explains this all without bringing up a lot of gray areas.
> 
> Does this help?  It was written before the release of D 2.0, but it does
> try to explain the difference between the different kinds of const:
> http://while-nan.blogspot.com/2007/06/you-cant-touch-this.html
> 
> As for the second thing, I'm not entirely sure either, but given that
> invariant(char)[] seems to have the behaviour one would expect from
> invariant(char[]), it could be that there's simply no difference and
> invariant(char)[] is the canonical form in the compiler.
> 
> 	-- Daniel



More information about the Digitalmars-d-learn mailing list