Difference betwee storage class and type (invariant/const)?
Daniel919
Daniel919 at web.de
Tue Jun 19 05:14:43 PDT 2007
> For example, what do these do differently?
>
> invariant int foo;
> invariant(int) foo;
There is a big difference.
invariant(int) foo;
1. the data of foo is an invariant int.
2. the brackets mean: you can assign another int to foo.
You can't change the data of foo.
But you are allowed to assign an other int to foo.
So this doesn't make sense for a simple storage type like int.
(for classes this is useful)
invariant int foo;
1. the data of foo is an invariant int.
2. the reference of foo is invariant, too
So you can't change the data of foo and you
can't assign an other int to foo.
And this makes sense ;)
(for classes this isn't possible, since they can't be assigned
at compile-time)
If you want the same thing for a class, you have to write:
final invariant(MyClass) foo = cast(invariant) new MyClass("mydata");
invariant(MyClass) foo;
You can't change the data of foo (like: foo.x=10;).
But you could assign an other MyClass to foo
(like: foo = cast(invariant) new MyClass("an other MyClass");)
final forbids the last step.
It means that you can't assign an other MyClass to foo.
This is equivalent: "final invariant(int)" and "invariant int".
It also shows the need for having 3 different keywords.
Even with explicit casting a class can't be assigned at compile-time:
invariant MyClass foo = cast(invariant) new MyClass("data");
//Error: non-constant expression cast(invariant MyClass)new MyClass
invariant(MyClass) foo = cast(invariant) new MyClass("data");
This is ok, but an other MyClass could be assigned to foo.
So we mark it as final:
final invariant(MyClass) foo = cast(invariant) new MyClass("data");
and get the same behavior as if we had:
invariant MyClass foo = cast(invariant) new MyClass("data");
//Error: non-constant expression cast(invariant MyClass)new MyClass
Just to mention it: const creates a read-only access to sth that might
be mutable.
invariant(MyClass*) ptr = ... //the data of MyClass will never ever change
const(MyClass*) ptr = ... //you can't use ptr to change the data, ptr is
pointing to
Please correct me, if I was wrong with anything.
Best regards,
Daniel
More information about the Digitalmars-d-learn
mailing list