www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Destructor for struct invoked many times

reply Antonio Corbi <acrb ggmail.com> writes:
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?
Jan 15 2019
parent reply rikki cattermole <rikki cattermole.co.nz> writes:
Because you passed it by value to writeln, which goes on to pass it to 
many other functions.
Jan 15 2019
parent Antonio Corbi <acrb ggmail.com> writes:
On Tuesday, 15 January 2019 at 10:49:17 UTC, rikki cattermole 
wrote:
 Because you passed it by value to writeln, which goes on to 
 pass it to many other functions.
Thanks Rikki! I was thinking about something like that. Antonio
Jan 15 2019