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

Daniel Keep daniel.keep.lists at gmail.com
Tue Jun 19 17:14:18 PDT 2007



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