Objects(from classes) at Compile time? no gc

Rikki Cattermole via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 15 23:40:31 PDT 2014


On 16/05/2014 4:59 p.m., 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?"

Rules about CTFE, I have:
1. It must be valid D code
2. Source code must be available during compilation
3. If its not passed to a function, its not available
4. You don't care about performance
5. Templates are your friend

I prefer to add pure to any function I intend to be CTFE'd.
So yes you can use new for classes at CTFE, just don't expect it to be 
collected and finalized.


More information about the Digitalmars-d-learn mailing list