not expected pointers for struct members from foreach
H. S. Teoh
hsteoh at quickfur.ath.cx
Tue Oct 9 16:20:02 PDT 2012
On Wed, Oct 10, 2012 at 12:59:08AM +0200, deed wrote:
> On Tuesday, 9 October 2012 at 16:21:47 UTC, bearophile wrote:
> >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.
[...]
> Meaning struct pointers are unusable or at least highly unreliable?
No, meaning if you want the struct to survive the end of the scope it's
declared in, you need to use new:
struct S {
// ... stuff
}
void main() {
S*[] ptrs;
foreach (i; 0..10) {
auto s = new S;
ptrs ~= s; // this is OK
}
// foreach (i; 0..10) {
// S s;
// ptrs ~= &s; // this is NOT OK
//}
}
T
--
Let X be the set not defined by this sentence...
More information about the Digitalmars-d-learn
mailing list