Bug 6499 – [GSoC] Destructor not called on object returned by method.
Status
RESOLVED
Resolution
FIXED
Severity
blocker
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
Other
OS
Windows
Creation time
2011-08-15T09:56:00Z
Last change time
2011-09-02T09:08:55Z
Keywords
patch, wrong-code
Assigned to
nobody
Creator
cristi.cobzarenco
Comments
Comment #0 by cristi.cobzarenco — 2011-08-15T09:56:42Z
Program:
import std.stdio;
struct Bar {
string m = "<not set>";
this( string s ) { writeln( "Constructor - ", m = s ); }
this( this ) { writeln( "Postblit - ", m ); }
~this() { writeln( "Destructor - ", m ); }
Bar bar() { return Bar( "bar" ); }
}
Bar foo() { return Bar( "foo" ); }
void main() {
foo().bar();
}
Output:
Constructor - foo
Constructor - bar
Destructor - foo
The object returned by bar() is not destroyed (leading to a memory leak in my GSoC project). Calling bar() directly, rather than on the result returned by foo() works properly. Saving the result of bar() in a named variable doesn't fix the problem (it creates three objects and destroys only two).
Comment #3 by cristi.cobzarenco — 2011-08-16T06:18:13Z
Thanks for the fix Kenji. However, this still doesn't work if bar() is a template function, i.e:
struct Bar {
string m = "<not set>";
this( string s ) { writeln( "Constructor - ", m = s ); }
this( this ) { writeln( "Postblit - ", m ); }
~this() { writeln( "Destructor - ", m ); }
// NOTE: bar is a template, otherwise it works
Bar bar()() { return Bar( "bar" ); }
}
Bar foo() { return Bar( "foo" ); }
void main() {
foo().bar();
}
Outputs:
Constructor - foo
Constructor - bar
Destructor - bar
Interestingly, this time it's the one returned by foo() that doesn't get destroyed, rather than the one returned by bar().