On 05/15/2014 09:59 PM, Taylor Hillegeist wrote:
The subject says it all really. i have this example:

import core.memory;

class fruit{
   int value=5;
   public int getvalue(){
     return value;
   }
}

int main(string[] args) {
     GC.disable;
     static fruit myfruit;
     return myfruit.getvalue();
}

Most of the smart people will see that i want the program to return 5
but I did something dumb and didn't put in the "new" statement?

So my question is in longer words "Can I create instances of objects at
compile time?" and if not "why not, i could build something
(roughly)equivalent out of structs and functions and have it at compile
time?"

Here are two ways of achieving it. Although f0 is constructed by new, I don't think that new is executed at run time (because it would conflict with 'static const'). f1 is definitely not using the GC because it is placed on a storage that the module owns:

class Fruit {
    int value;

    this (int value)
    {
        this.value = value;
    }

    public int getvalue() const {
        return value;
    }
}

static const f0 = new Fruit(42);

ubyte[__traits(classInstanceSize, Fruit)] storage;
static const Fruit f1;

static this()
{
    import std.conv;
    f1 = emplace!Fruit(storage[], 43);
}

void main() {
    assert(f0.getvalue() == 42);
    assert(f1.getvalue() == 43);
}

Ali

Reply via email to