immutable and static this()
Jonathan M Davis
jmdavisProg at gmx.com
Mon Mar 21 14:48:16 PDT 2011
> On Mon, 21 Mar 2011 22:27:17 +0100, teo <teo.ubuntu at yahoo.com> wrote:
> > I cannot initialize immutable class members inside a static this()
> > constructor. Is there any reason for that?
> >
> > Example:
> > class Test
> > {
> >
> > public immutable(int) x;
> > static this()
> > {
> >
> > x = 1; // Error: variable Test.x can only initialize const x
> >
> > inside constructor
> >
> > }
> >
> > }
>
> Non-static class members require a this pointer, and thus cannot be
> initialized in a static constructor. However, if that is the error
> message you get, it is clearly misleading.
No. Error message is essentially correct, just confusing. In this case, x is a
member variable, _not_ a class/static variable. So, it must either be directly
initialized
public immutable int x = 1;
or in a constructor (and in this case the constructor would have to be
immutable).
public immutable int x;
this() immutable
{
int x = 1;
}
static this() in a class is for initializing class/static variables only, so
if you did
public static immutable int x;
static this()
{
int x = 1;
}
that would work. The fact that it is immutable has nothing to do with whether
it is a member variable or a class/static variable, so it has no effect on
whether a normal or static constructor is used.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list