Bug 5353 – clear function is calling the destructor twice
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
druntime
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-12-14T13:24:00Z
Last change time
2010-12-15T12:36:39Z
Assigned to
sean
Creator
craigblack2
Comments
Comment #0 by craigblack2 — 2010-12-14T13:24:16Z
struct A
{
~this() { writeln("here"); }
}
void main()
{
A *a = new A;
clear(*a);
}
prints out:
here
here
Comment #1 by nfxjfg — 2010-12-14T14:00:42Z
I think it's only because the GC calls the destructor AGAIN, when the programs exits. This is as designed. First, the clear() function doesn't delete the object. Second, the GC calls dtors on all live objects on exit. Thus, the dtor is called twice.
So, this bug is likely INVALID.
As for the clear() function, its design is an embarrassment.
Comment #2 by nfxjfg — 2010-12-14T15:16:49Z
Craig reminded me on d.D.bugs that this is a struct, not a class. He's right. Maybe the dtor gets called additionally because temporaries of the struct are copy constructed.
It doesn't have to do with the GC and is a different problem.
Comment #3 by simen.kjaras — 2010-12-14T16:35:59Z
Highly interesting: copying the clear function of object_.d in druntime to my own module, the destructor is called but once.
void myclear(T)(ref T obj) if (is(T == struct))
{
static if (is(typeof(obj.__dtor())))
{
obj.__dtor();
}
auto buf = (cast(void*) &obj)[0 .. T.sizeof];
auto init = (cast(void*) &T.init)[0 .. T.sizeof];
buf[] = init[];
}
struct test {
~this( ) {
writeln( "dtor!" );
}
}
void main( ) {
test* p = new test;
clear( *p );
}
Comment #4 by simen.kjaras — 2010-12-15T02:02:20Z
This looks fixed in the newest beta. Anyone else care to check?
Comment #5 by schveiguy — 2010-12-15T05:48:18Z
I still see 2 clears on Linux with the latest beta.
Comment #6 by schveiguy — 2010-12-15T06:19:56Z
Figured out the problem. The runtime creates a temporary copy of the struct in order to copy over the initial value.
It is fixed by copying the TypeInfo.init data.
I'll check in a change after the beta is released (don't want to interfere with that).
But long story short, your dtor is getting called twice, but the first time it is called, it's on a default-constructed instance, so it shouldn't cause a problem.