Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why some features need GC?

Tags:

d

Why appending to an array needs GC?

C++ doesn't need it. How come turning off GC makes some features leak.

If I'm not mistaken, D is designed [to be able] to be used without GC.

Please, give a comprehensive answer.

like image 764
Hrisip Avatar asked Nov 29 '25 08:11

Hrisip


2 Answers

"Why do some features need GC?" is a simple question to answer: because D was designed with a GC in mind. The GC enables the programmer to write code a certain way, and turning it off means you can't write code that way. Specifically, it takes care of cleaning up memory for you, so when you turn it off, you need to do that manually.

Steven Schveighoffer's article on D slices covers the topic of D slices (aka arrays) very well.

D's slices do not own the data they're pointing to - the runtime does. That means multiple slices may point to the same data, and they don't have to figure out which one of them is responsible for free()-ing the data when it's no longer needed. In C++ you could do this with a shared_ptr<T[]>, if I understand correctly (it's been a few years since I did much C++). shared_ptr has the same issues other reference-counted system have - partiularly circular references. A GC does the same thing with less hassle, at the cost of sometimes using more memory or being slower (though it should be said that RC can have the exact same issues, just under different circumstances).

As for D being designed for use without GC - no, not really. It was originally designed with a GC in mind, and it has acquired some features that make working without a GC much easier. Chief among these is @nogc, which says 'this function may not allocate through the GC, and may not call any functions that may allocate through the GC'. When a function is marked @nogc, the compiler enforces this, refusing to compile code that breaks this promise.

There are libraries that afford some of the same comforts that are available in standard code, in @nogc code. I have no experience with them, but Tanya and nogc are two examples. I haven't looked closely at how they do their thing, but I would assume they are using RC as well.

like image 159
BioTronic Avatar answered Dec 02 '25 06:12

BioTronic


I would say it quite opposite. D has been designed with GC in mind. So many builtin features are dependent on GC.

There has been an effort lately to make D less dependant on GC.

About arrays there is nice article on D site:

https://dlang.org/articles/d-array-article.html

like image 25
Kozzi11 Avatar answered Dec 02 '25 05:12

Kozzi11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!