How to create nogc code?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 11 14:28:58 PDT 2016


On Monday, July 11, 2016 03:51:27 Adam Sansier via Digitalmars-d-learn wrote:
> You know, you don't see your argument much in C++ forums. In
> fact, it's probably the opposite ;)

C++ doesn't have a GC built-in and does not have features that rely on it.
So, it's in a very different situation. And when talking about the GC in D
and how avoiding the GC causes problems, you're usually talking about
features that C++ doesn't even have. If you never use features like D's
dynamic arrays or delegates, then it's mostly a non-issue.

If all you're doing is passing around int* and the like, then the situation
is the same as in C and is fine. But stuff like int[] becomes problematic,
because it assumes that you're using the GC. But that's stuff that doesn't
exist in C++.

The main area that's a problem in D that isn't a problem in C++ that
involves features that C++ has is allocating user-defined objects in that
C++'s new does not use the GC, whereas D's does, and in both cases, new is
the clean and easy way to allocate an object. So, unlike in C++, in D, if
you want to put user-defined objects on a non-GC heap, it can be a pain -
since malloc and free don't handle that for you; they just deal with the
memory itself. You need a wrapper that handles not only the allocation, but
the construction and destruction correctly. But std(.experimental).allocator
is where that's getting fixed. So, fortunately, that problem is going away,
but without those wrappers, avoiding the GC gets miserable fast.

So, if you stick purely to features that don't use the GC at all, then you
lose out on some nice features, but you're in a similar boat to C or C++,
and you don't need to worry about the GC, since you're not using it, and
you're not using anything that's designed to use it. But then you have to
avoid some nice features, which sucks, and makes writing your programs
harder than they would be otherwise. By far the bigger gain is writing your
code in a way that minimizes heap allocations in general, and that's going
to be of benefit whether you're using the GC or not (and that's just as true
in C++ as it is D).

Because their feature sets are different, the situations in C++ and D are
fundamentally different even though they're similar languages, and I
wouldn't expect the same arguments or conclusions on all of the various
topics in a C++ discussion that you'd have in a D discussion, even if the
folks making those arguments were the same. Sometimes, the best way to do
things is exactly the same in both languages, and sometimes it's very
different.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list