digitalmars.D.learn - Destructor for struct invoked many times
- Antonio Corbi (32/32) Jan 15 2019 Hi,
- rikki cattermole (2/2) Jan 15 2019 Because you passed it by value to writeln, which goes on to pass it to
- Antonio Corbi (5/7) Jan 15 2019 Thanks Rikki!
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
Because you passed it by value to writeln, which goes on to pass it to many other functions.
Jan 15 2019
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