[Dlang-internal] Strange behavior when appending pointers of structs to arrays
Jonathan M. Wilbur
jonathan at wilbur.space
Sat Feb 3 12:19:08 UTC 2018
Given the following code:
import std.stdio : writeln;
---
struct Foo
{
Foo*[] children;
void value()
{
Foo bar = Foo();
version (bad1)
{
this.children ~= &bar;
}
version (bad2)
{
this.children.length += 1u;
this.children[$-1] = &bar;
}
}
void bark()
{
writeln("children: ", this.children.length);
writeln("grandchildren: ",
this.children[0].children.length);
}
}
void main ()
{
Foo foo = Foo();
version (good)
{
Foo bar = Foo();
foo.children ~= &bar;
}
else
{
foo.value();
}
foo.bark();
}
---
The resulting executable returns the following outputs:
C:\Users\Jonathan\Desktop\bug>dmd .\bug.d -version=bad1
C:\Users\Jonathan\Desktop\bug>bug.exe
children: 1
grandchildren: 4203068
C:\Users\Jonathan\Desktop\bug>dmd .\bug.d -version=bad2
C:\Users\Jonathan\Desktop\bug>bug.exe
children: 1
grandchildren: 1
C:\Users\Jonathan\Desktop\bug>dmd .\bug.d -version=good
C:\Users\Jonathan\Desktop\bug>bug.exe
children: 1
grandchildren: 0
Why?
More information about the Dlang-internal
mailing list