Thread overview | |||||
---|---|---|---|---|---|
|
January 15, 2019 Destructor for struct invoked many times | ||||
---|---|---|---|---|
| ||||
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? |
January 15, 2019 Re: Destructor for struct invoked many times | ||||
---|---|---|---|---|
| ||||
Posted in reply to Antonio Corbi | Because you passed it by value to writeln, which goes on to pass it to many other functions. |
January 15, 2019 Re: Destructor for struct invoked many times | ||||
---|---|---|---|---|
| ||||
Posted in reply to rikki cattermole | 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
|
Copyright © 1999-2021 by the D Language Foundation