Bug 9084 – Structs assignment and associative arrays

Status
RESOLVED
Resolution
DUPLICATE
Severity
normal
Priority
P2
Component
druntime
Product
D
Version
D2
Platform
All
OS
All
Creation time
2012-11-27T10:52:00Z
Last change time
2012-12-13T09:59:34Z
Keywords
wrong-code
Assigned to
nobody
Creator
maxim

Comments

Comment #0 by maxim — 2012-11-27T10:52:35Z
Assigning structs to AA arrays causes bugs due to incomplete object construction: import std.stdio; struct S { int i = 42; struct SS { int ii = 41; this(this) { writeln("SS postblit"); } void opAssign(SS rhs) { writeln("SS opAssign"); } ~this() { writeln(ii);} } SS ss; this(this) { writeln("S postblit"); } void opAssign(S rhs) { writeln("S opAssign"); } ~this() { writefln("i=%d, ii=%d", i, ss.ii); } } S[int] map ; // S[2] map; // S[] map = [S(), S()]; void main() { map[1] = S(); } Here program will produce not 41 and 42, but some arbitraly values because when druntime allocates space for a new struct object in array, it does not initialize it. Switching to fixed/dynamic array fixes program. This causes segfault in phobos because of false assumptions about valid state of the object: import std.typecons; import std.stdio; alias RefCounted!(int) Foo; Foo[int] map; unittest { map[1] = Foo(); } void main() { } In this code a Foo() instance is assigned into allocated but not constructed object and because struct assignment is rewritten to opAssign call, on entering Foo.opAssign "this" points to non-constructed object which breaks code which assumes that object is acrually valid.
Comment #1 by maxim — 2012-12-13T09:59:34Z
*** This issue has been marked as a duplicate of issue 6178 ***