not expected pointers for struct members from foreach
bearophile
bearophileHUGS at lycos.com
Tue Oct 9 08:57:47 PDT 2012
deed:
> // Again, why are the three last adresses the same?
The D language and its compiler is acting correctly here, so the
output you see is correct. All those structs are allocated on the
stack. The first three Test are allocated on the stack. In the
loop it allocates the first struct on the stack, and it gets
destroyed. Then when the successive loop enters, it creates a new
struct, and it uses the same stack space.
See:
import std.stdio;
struct Test {
static Test*[] psObject;
int x;
this(int a) {
x = a;
psObject ~= &this;
}
~this() {
writeln(x);
}
}
void main() {
Test(0);
foreach (i; 1 .. 3)
Test(i);
Test.psObject.writeln();
}
0
1
2
[12FE48, 12FE54, 12FE54]
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list