I just got it! (invariant/const)

Simen Kjaeraas simen.kjaras at gmail.com
Wed Apr 9 15:37:10 PDT 2008


On Wed, 09 Apr 2008 20:40:38 +0200, Janice Caron <caron800 at googlemail.com>  
wrote:

> What you're describing is something different - a non-invariant class
> with invariant members. Well, the only time you can assign an
> invariant member is at compile-time. That means they have to be
> assigned with compile-time constants. That, in turn, means they might
> as well be static, because they are not going to differ from instance
> to instance. And /that/ means you can rewrite your counterexample as
>
>     class C
>     {
>         static invariant int x = 4;
>
>         static int getX() pure
>         {
>             return x;
>         }
>     }
>
>     auto c = new C(4);
>     int n = c.getX;
>
> Now getX() is pure because it's static, and therefore /has/ no this  
> pointer.

class foo
{
	invariant int bar;
	
	this()
	{
		bar = 4;
	}
}

This works under DMD 2.012. However, this does not work:

class foo
{
	invariant int bar = 2;
	
	this()
	{
		bar = 4;
	}
}

There is nothing wrong with having non-static, invariant member variables,  
which are assigned in the constructor. Of course, you'd get the exact same  
result (except for function which require invariant parameters, i.e. pure  
functions) with a const int.

-- Simen



More information about the Digitalmars-d mailing list