D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 6998 - std.container.Array destroys class instances
Summary: std.container.Array destroys class instances
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P2 normal
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2011-11-23 16:40 UTC by Nils
Modified: 2014-04-12 11:54 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Nils 2011-11-23 16:40:00 UTC
---
class C {
	int i;
}
auto c = new C;
c.i = 42;
Array!C a;
a ~= c;
a.clear;
assert(c.i == 42); // fails
---

Tested with dmd 2.056.
Problem does not arise with structs.
Comment 1 Nils 2012-01-21 01:34:19 UTC
This happens:
Array!T.Payload's destructor does
---
foreach (ref e; _payload) .clear(e);
---
where .clear is object.clear:
---
void clear(T)(T obj) if (is(T == class))
{
    rt_finalize(cast(void*)obj);
}
void clear(T)(ref T obj)
    if (!is(T == struct) && !is(T == class) && !_isStaticArray!T)
{
    obj = T.init;
}
---
(and other overloads that are not of interest)
That is, when object.clear is given a class instance reference, it destroys the
object, and when given a pointer (e.g. to a 'new'ed struct instance),
it nulls the pointer, but doesn't touch the pointer's target.

So maybe Array shouldn't call object.clear, or it should check for
!is(T == class). Or maybe object.clear shouldn't destroy class instances. To me
this would look more in line with the other versions of object.clear:
---
void clear(T)(ref T obj) if (is(T == class))
{
    obj = T.init;
}
---
Comment 3 github-bugzilla 2014-04-12 11:54:14 UTC
Commits pushed to master at https://github.com/D-Programming-Language/phobos

https://github.com/D-Programming-Language/phobos/commit/86b117ed576a4f6c28db014c3ccccf31c79d0f76
Fix Issue 6998 - std.container.Array destroys...

... class instances

https://github.com/D-Programming-Language/phobos/commit/e9e8d93ce15abfb62e8c803ca261ab1813852004
Merge pull request #2079 from monarchdodra/6998

Fix Issue 6998 - std.container.Array destroys class instances