What should happen here?

Walter Bright newshound2 at digitalmars.com
Sat Sep 25 22:19:30 UTC 2021


On 9/25/2021 10:46 AM, Steven Schveighoffer wrote:
> Right, but the optimizer is working against that.
> 
> For example:
> 
> ```d
> auto c = new C;
> .... // a whole bunch of other code
> 
> c.method; // not necessarily still live here.
> ```
> 
> Why would it not be live there? Because the method might be inlined, and the 
> compiler might determine at that point that none of the data inside the method 
> is needed, and therefore the object is no longer needed.
> 
> So technically, it's not live after the original allocation. But this is really 
> hard for a person to determine. Imagine having the GC collect your object when 
> the object is clearly "used" later?

I understand your point. It's value is never used again, so there is no reason 
for the GC to hold on to it. After the point when the value is never used again, 
when the destructor is run is indeterminate. Maybe the real problem is the user 
is expecting the destructor to run at a specific point in the execution.

The point of putting the variable on the stack (or in a register, it works the 
same) is so the GC can find it. If D code is being called, D does not allow the 
hiding of pointers. But C does allow this, such as when doing the singly linked 
list XOR trick. The GC won't find those pointers, and will collect them. But if 
the pointer is still on the stack, the GC will find them.

If the function is inlined, it is not C code, so hiding the pointer won't be 
allowed, and it's not a problem.


>> Do *not* use the GC to manage non-memory resources.
> When D uses the GC for delegates, classes, etc, and you want to hook to those 
> things via C callbacks, this advice falls flat.

If the closure for a delegate is located on the stack, then it will be found by 
the GC and works fine. If the closure is located on the GC heap, and the OS will 
keep it around past the return, then you'll need to use addRoot.


> Basically, you are saying, when using your OS primitives, don't use D.

addRoot()


More information about the Digitalmars-d mailing list