Bug 19386 – Destructor not called when constructed inside if condition, leading to memory leak

Status
RESOLVED
Resolution
FIXED
Severity
critical
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2018-11-10T00:35:22Z
Last change time
2019-05-22T01:35:59Z
Assigned to
No Owner
Creator
Jesse Bruce

Comments

Comment #0 by jesse.bruce — 2018-11-10T00:35:22Z
Destructor is not called when an object is constructed inside of an if statement and opCast!bool returns false. Reproduction: struct Thing { this(int* i) { ptr = i; (*ptr)++; } ~this() { (*ptr)--; } T opCast(T:bool)() { return false; } int* ptr; } Thing makeThing(int* p) { return Thing(p); } void main() { int i; { if(auto t = makeThing(&i)) { import std.stdio; writeln("hello?"); } } assert(i == 0); } Observed output: [email protected](24): Assertion failure Expected output:
Comment #1 by jesse.bruce — 2018-11-10T00:38:16Z
Moving object creation outside of the if statement works as intended. struct Thing { this(int* i) { ptr = i; (*ptr)++; } ~this() { (*ptr)--; } T opCast(T:bool)() { return false; } int* ptr; } Thing makeThing(int* p) { return Thing(p); } void main() { int i; { auto t = makeThing(&i); if(t) { import std.stdio; writeln("hello?"); } } assert(i == 0); } Observed output:
Comment #2 by dlang-bot — 2019-05-22T01:35:59Z
dlang/dmd pull request #9830 "Fix issue 19386 - Destructor not called when constructed inside if condition" was merged into stable: - 9d4f5555118670ef68416a0d13108e3cdcf13271 by سليمان السهمي (Suleyman Sahmi): Fix issue 19386 - Destructor not called when constructed inside if condition This happens when the if condition evaluates to false at runtime https://github.com/dlang/dmd/pull/9830