Constancy of invariants

Stewart Gordon smjg_1998 at yahoo.com
Sun Jan 29 08:08:11 PST 2012


Discussion about
http://d.puremagic.com/issues/show_bug.cgi?id=7369
has got me thinking.

On discovering that DMD (2.057) rejects
     invariant() const {}
I had made out that constancy doesn't apply to invariants.  Only later did I realise it 
does, but requires the syntax
     const invariant() {}

But thinking of it, why should one have to declare invariants as const at all?

Invariants are used to check the integrity of the object, not to modify it, and so it 
would seem natural that invariants should be automatically const.

The way it is, a type with a non-const invariant cannot have any public const methods.  I 
can see people sacrificing either invariants or const-correctness to get around this, 
before they discover the syntax that works for declaring a const invariant.

Notice also that DMD rejects two or more invariants in a single type

     invariant() {}
     const invariant() {}
     immutable invariant() {}

so, unless this is a bug, it isn't in order to have different checks depending on the 
constancy of either the object or the method called thereon.

What exactly is the intended behaviour here?

And what's your view?  Should we make invariants automatically const?

Stewart.


More information about the Digitalmars-d mailing list