invariant/const class storage class
Neil Vice
sardonicpresence at gmail.com
Tue Sep 30 19:49:36 PDT 2008
Nicolas Sicard wrote:
> Hi,
> I had a look at http://www.digitalmars.com/d/2.0/class.html#ConstClass.
> Does this mean that I should be able to write something like :
>
> module test;
>
> invariant class Thing {
> private int _field;
>
> this(int field) {
> _field = field;
> }
>
> int field() {
> return _field;
> }
> }
>
> ?
> It doesn't compile:
>
> Error: cannot implicitly convert expression (this) of type
> invariant(Thing) to test.Thing
>
> The error doesn't mention any line. I don't undestand it.
> I thought it would be a way of saying that instances of a class are
> always const or immutable.
> Sorry if I said something stupid :-) ...
>
> Nicolas
My understanding is that by applying a const/invariant specifier to a
class type you are effectively indicating that its "this" reference has
that specifier.
So in this case, in the constructor where you attempt to assign to
_field, you are attempting to modify an invariant "this" variable, which
is not permitted.
The compiler error message is due to it attempting to implicitly cast
the invariant(Thing) to a non-invariant Thing in order to assign to its
member.
If my understanding is correct I am not sure how invariant classes would
be useful as they could only have invariant fields and as such would
seem to be sort of a collection of constants.
Undoubtedly however, I will be corrected =P
More information about the Digitalmars-d
mailing list