Advice wanted on garbage collection of sockets for c++ programmer using D
Guillaume Piolat via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jun 27 05:29:03 PDT 2017
On Tuesday, 27 June 2017 at 09:54:19 UTC, John Burton wrote:
> I assume that I do need to explicitly call close on the socket
> as there is no deterministic destructor for class objects.
Yes.
> I further assume that the runtime will garbage collect any
> memory allocated to the socket object at a later time.
Most probably.
>
> Am I doing this right with GC? In C++ I'd ensure that the
> Socket class had a destructor that closed the socket and I'd
> also assume that once it went out of scope there was no memory
> left allocated. In D am I right to assume I need to manually
> close the socket but there is no need to worry about the memory?
Yes.
You can also call a destructor manually with destroy(obj);
This avoids having a forest of 'close' methods, who are
duplicates of the destructor in spirit, and let's you use
destructors like you are accustomed in C++.
Generally, it is dangerous to let the GC handle resource release:
https://p0nce.github.io/d-idioms/#The-trouble-with-class-destructors
> Now the issue is that I now need to call this function more
> than once every second. I worry that it will create large
> amounts of uncollected "garbage" which will eventually lead to
> problems.
If this is a problem you can create it on the stack with
std.typecons.scoped
> Am I doing this right? Or is there a better way to do this in D?
>
What you are doing it OK.
More information about the Digitalmars-d-learn
mailing list