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

Robert Fraser fraserofthenight at gmail.com
Tue Jun 19 14:15:28 PDT 2007


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.


More information about the Digitalmars-d-learn mailing list