Non-constant expression error

Jarrett Billingsley kb3ctd2 at yahoo.com
Wed Aug 22 04:46:51 PDT 2007


"Márcio Faustino" <m.faustino at no.spam.gmail.com> wrote in message 
news:fah26g$2ctr$1 at digitalmars.com...
> Hi,
>
> Does someone knows why isn't possible to do something like this:
>
> //-------------------------------------------
> import std.regexp;
>
> class A {
> RegExp pattern = new RegExp(".*");
> }
>
> RegExp[] patterns = [new RegExp(".*")];
> //-------------------------------------------
>
> Thanks,

Because those expressions aren't constant.  Hate to sound obvious XD

You can't use non-constant expressions (like function calls (well.... 
because of CTFE sometimes those are legal), 'new') as the initializer to 
globals or class members because the compiler builds up their initializers 
in the static data segment.  Fortunately there are ways to do this:

class A
{
    RegExp pattern;

    this()
    {
        // Initialize dynamic members in the constructor.
        pattern = new RegExp(".*");
    }
}

RegExp[] patterns;

static this()
{
    // Initialize dynamic globals in a static constructor.
    patterns = [new RegExp(".*")];
} 




More information about the Digitalmars-d-learn mailing list