Can't I allocate at descontructor?

Ali Çehreli acehreli at yahoo.com
Fri Mar 5 20:28:58 UTC 2021


On 3/5/21 12:24 PM, Jack wrote:

> Are there some kind of replacement or I have to make my own 
> finalize-like method, once I determine somewhat the application no 
> longer need those resources?

destroy() executes the destructor.

To my surprise, even though 'c' is not null below, the destructor is not 
executed multiple times.

import std.stdio;

class C {
   string fileName;

   this(string fileName) {
     writeln("constructing");
     this.fileName = fileName;
     writeln("creating file");
   }

   ~this() {
     writeln("destructing");
     if (fileName) {
       writeln("removing the file");

     } else {
       writeln("NOT removing the file");
     }
   }
}

void main() {
   auto c = new C("some imaginary file name");

   // Executes the destructor
   destroy(c);

   // This does not do anything
   destroy(c);

   // Neither does this
   import core.memory;
   GC.collect();
}

Ali


More information about the Digitalmars-d-learn mailing list