Destructor for struct invoked many times

Antonio Corbi acrb at ggmail.com
Tue Jan 15 10:46:51 UTC 2019


Hi,

In this simple example, the destructor for the struct is invoked 
four more times than expected:

----
import std.stdio;

struct Person {
   string name;
   int age;

   ~this() {
     writefln("%s is gone (0x%x)", name, &this);
   }
}

int main(string[] args) {
   Person* p = new Person;

   writefln ("Created person (0x%x)", p);
   p.name = "Peter";
   p.age = 23;

   writeln("Person:", *p); // Comment this line and try

   return 0;
}
----

Output:

Created person (0x7f85ee997000)
Person:Person("Peter", 23)Peter is gone (0x7ffd916c1560)
Peter is gone (0x7ffd916c15c0)

Peter is gone (0x7ffd916c1640)
Peter is gone (0x7ffd916c16f0)
Peter is gone (0x7f85ee997000)
-----

If I comment the line "writeln("Person:", *p);" then the 
destructor is invoked only one time as expected.

Why is it?


More information about the Digitalmars-d-learn mailing list