Mem Mgmt: With & Without the GC

Guillaume Piolat via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 21 12:30:51 PDT 2016


On Sunday, 21 August 2016 at 16:14:53 UTC, Zane wrote:
> Hey all,
>
> My knowledge of GCs is limited, but my faith in them (for most 
> applications) has greatly increased with advances (like with 
> Golang's recent updates). I am now trying to get a better sense 
> for the direction D is going regarding memory management, both 
> in relation to the GC and without it. Excuse my ignorance, but 
> can someone clarify the following for me?
>
> 1) If using the GC, but for whatever reason, I need to free 
> something _right now_, is core.GC.free() the proper way to do 
> this?

If you need to destroy a class object right now, the proper way 
is to call .destroy on it (or use something that uses it like 
Scoped!T, Unique!T, Refcounted!T...).

If you need to destroy a struct object right now, the proper way 
is to end the scope.

If you need to free memory right now, better not allocate it from 
the GC, but instead with malloc/free. The GC does not guarantee 
to collect freed memory when you want.


> 2) Does calling object.destroy() mean that the object is marked 
> for future collection? If not, how can I ensure it is properly 
> marked.

Calling .destoy on an object calls its destructor but does not 
mark it for collection.

Objects are collected when they are not reachable anymore.
At this point, the destructor is called if it wasn't already (and 
then the object is overwritten with .init).

Actually you shouldn't have to worry when an object memory is 
collected.


> 3) How can I mark a non-object for future collection? For 
> example, a dynamic array: int[] a = new int[10];. Do I just set 
> any references to null?

Yes, it is marked for future collection when it's not reachable 
anymore.

Then again, the GC might not reclaim memory right now because 
it's imprecise and you could have "false pointers".


> 4) What if I want to immediately deallocate a dynamically 
> allocated non-object (such as the dynamic array) - Can I use 
> core.GC.free?

I don't know if this will deallocate with 100% certainty.

> 5) Is there a way to do simple heap allocation with 'new' while 
> ensuring the GC doesn't deallocate until I want it to?

Keep a reference somewhere reachable (by default: stack, heap, 
globals: everything is reachable and scanned).


> 6) If the GC is off, how is allocation/deallocation handled?

If you have called GC.disable, no GC collect is performed on any 
allocation.
This is only suitable if you don't have a long-running software 
that would risk running out of memory.
This is known to speed-up short processes.

> Can I still use new for example

You can still use new.

> (and how do I dealloc)?

I don't know then if you can deallocate.





More information about the Digitalmars-d-learn mailing list