On Friday, 8 August 2014 at 16:51:37 UTC, H. S. Teoh via
Digitalmars-d-learn wrote:
On Fri, Aug 08, 2014 at 04:42:12PM +0000, seany via
Digitalmars-d-learn wrote:
consider this :
struct S
{
/* ... */
}
void main()
{
ulong [] u;
for(// ...
{
S s_instance;
// fillup .. S.key = value;
u ~= cast(ulong)*s_instance;
}
}
however, the structs are being allocated to the same place.
Because,
Every time the iterator ends an iteration, seemingly,
s_instance is
collected as garbage.
This has nothing to do with the GC. You're storing an address
to a local
variable on the stack, which is bad idea because once it goes
out of
scope, it will get overwritten by other data (such as subsequent
instances of itself in the loop body).
You need to explicitly allocate the struct on the heap with
'new' if you
want it to survive past the end of the loop body:
S* s_instance = new S();
u ~= cast(ulong)s_instance;
Note that as long as you have pointers to the struct, the GC
will not
collect it. So you actually don't need to worry about freeing
the data
once you're done with it; just set all pointers to it to null,
and the
GC will collect it for you.
T
Okey, thank you.
And as discussed earlier, I was trying to save the pointers in an
ulong (which is same as size_t or ptr_t, those are aliased)
array, but both addresses 7ff11330eeb0 and 7ff11330ed00 is saved
as 140733974163440.
What do I do?