Mem Mgmt: With & Without the GC

Cauterite via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 21 12:28:09 PDT 2016


On Sunday, 21 August 2016 at 18:31:26 UTC, Zane wrote:
> I see - That makes sense, but is there no way to "pause/stop" 
> the GC, but still be able to use the 'new' syntax?

Oh you can use `new` when the GC is disabled, no problem. All the 
GC's functionality is still available.

But be careful about what I said with `new` not returning the 
base of the allocation. It might not be safe to explicitly 
`free()` memory allocated by `new` if there could be multiple 
objects in the same memory block. I honestly don't know the facts 
about this.

You can always `GC.free()` memory you've allocated yourself with 
`GC.malloc()`, so malloc+emplace is an option. You could define a 
template to give more convenient syntax.

Also I think you can overload the `new` operator. I've never 
tried it.

> Regarding the marking, I guess my question is: what must be 
> done to ensure something allocated with 'new' will be a 
> candidate for auto-collection later (when GC is enabled)?

I don't think it's possible with a conservative garbage 
collector, because anything that looks like a pointer to your 
object can prevent it from being collected.

However, if there are no actual live pointers to it, the chances 
that it will be collected are very high, especially on 64-bit 
systems.

So for now, your best bet is to make sure your object is not 
accessible (set all live pointers to it to null). It will only 
stay in memory if you're very unlucky.

Once we have a precise garbage collector (should be soon) you can 
be sure an object will get collected if it is not accessible from 
any live pointers.

--------------------------------------

By the way, when I say "live pointer", I mean a pointer which is 
accessible (through any number of indirections) from the memory 
roots.

e.g. If you have a linked list on the heap, with each node 
pointing to the next, but no other pointers to any of the nodes 
(e.g. from the stack) those pointers are not live. The list as a 
whole is not accessible.


More information about the Digitalmars-d-learn mailing list