Explicitly avoid GC of objects?

Benjamin Schaaf ben.schaaf at gmail.com
Tue May 21 13:23:54 UTC 2019


On Tuesday, 21 May 2019 at 11:54:08 UTC, Robert M. Münch wrote:
> Is there a trick to accomplish 2 when objects are created from 
> different scopes which need to be kept? So, I have one function 
> creating the objects and one using them. How can I keep things 
> on the stack between these two functions?
>
> How is 3 done? Is this only useful for static variables?

I'll try to describe rules 2 and 3 as simply as possible: As long 
as you can access the pointer to gc allocated memory in D it will 
not be freed.

So whether that pointer lives on the stack:

int* foo() {
     return new int;
}
void bar() {
     int* a = foo();
     c_fn(a);
}

In static or thread local memory:

int* a;
__gshared int* b;
void bar() {
     a = new int;
     c_fn(a);
     b = a;
     c_fn(b);
}

Or on the heap:

class D {
     int* a;
}
void bar() {
     D d = new D(new int);
     c_fn(d.a);
}

Doesn't really matter.


More information about the Digitalmars-d-learn mailing list