invariant/const class storage class
Simen Kjaeraas
simen.kjaras at gmail.com
Wed Oct 1 00:47:54 PDT 2008
On Wed, 01 Oct 2008 04:49:36 +0200, Neil Vice <sardonicpresence at gmail.com>
wrote:
> 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
Unless I've misunderstood, you are indeed correct. I also thought you'd be
allowed to create invariant objects by using an invariant constructor, but
that seems not to be the case.
Is this really correct behavior? How then are we supposed to initialize our
invariant objects?
--
Simen
More information about the Digitalmars-d
mailing list