Garbage Collector?

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Fri Apr 28 08:23:18 PDT 2017


On Fri, Apr 28, 2017 at 09:01:03AM +0000, Moritz Maxeiner via Digitalmars-d wrote:
> On Friday, 28 April 2017 at 07:35:00 UTC, Ben wrote:
[...]
> > Is it so hard for developers when you declare a variable, to later
> > also clean it up???
> > 
> > var x = 1;
> > // Do work
> > x.free;
> 
> If you write it like that, yes, because often it's not just one such
> make/dispose pair per scope, but multiple, possibly overlapping ones
> and people make mistakes. And the more complex a piece of code gets
> the harder it becomes to decipher such pairs and/or decide if the
> "closing" dispose is missing.
> This is one of the reasons why scope guards are good:
> 
> var x = 1;
> scope (exit) x.free
> // Do work
> 
> This, as code becomes more complex, allows for much easier reading
> (and understanding) of lifetimes.
[...]

Elephant in the room: D lets you call the C library's malloc() and
free(). If you absolute insist that you don't want to use the GC, go
right ahead and import core.c.stdlib, and malloc and free away.  As
mentioned above, D's scope guards will even help you avoid mistakes by
keeping allocation and free in the same scope together, i.e., instead of
writing:

	auto x = malloc(...);
	// do stuff
	// and more stuff
	// and more stuff
	// so many pages of stuff you forgot about x
	free(x);	// very likely you'll forget this by now

you could save yourself the bug by writing:

	auto x = malloc(...);
	scope(exit) free(x);
	// ... however many pages of stuff you want, you don't have to
	// remember to write free() afterwards!

Yes, D comes with a GC... doesn't mean you have to use it if you don't
want to, though!


T

-- 
Doubt is a self-fulfilling prophecy.


More information about the Digitalmars-d mailing list