Hello, folks! Newbie to D, have some questions!

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Feb 19 04:31:51 PST 2017


On 02/19/2017 12:51 PM, timmyjose wrote:
> a). So the GC is part of the runtime even if we specify @nogc

Yup. @nogc is per function, not per program. Other functions are allowed 
to use the GC.

> b). Do we manually trigger the GC (like Java's System.gc(), even though
> that's not guaranteed), or does it get triggered automatically when we
> invoke some operations on heap allocated data and/or when the data go
> out of scope?

You can trigger a collection manually with GC.collect [1]. Otherwise, 
the GC can do a collection when you make a GC-managed allocation. If you 
don't make GC allocations, e.g. because you're in @nogc code and the 
compiler doesn't allow you to, then no GC collections will happen.

> c). Does Rust have analogues of "new" and "delete", or does it use
> something like smart pointers by default?

D, not Rust, right?

D uses `new` for GC allocations. `new` returns a raw pointer or a 
dynamic array (pointer bundled with length for bounds checking).

There is `delete`, but it's shunned/unfashionable. Maybe it's going to 
be deprecated, I don't know. You're supposed to let the GC manage 
deletion, or use `destroy` [2] and GC.free [3] if you have to do it 
manually.

Of course, you can also call C functions like `malloc` and `free` and do 
manual memory management.

Regarding smart pointers, I'm not up to speed. There's 
std.typecons.Unique [4], but I don't know how it compares to other 
languages.


[1] https://dlang.org/phobos/core_memory.html#.GC.collect
[2] https://dlang.org/phobos/object.html#.destroy
[3] https://dlang.org/phobos/core_memory.html#.GC.free


More information about the Digitalmars-d-learn mailing list