Advice wanted on garbage collection of sockets for c++ programmer using D

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 27 03:13:56 PDT 2017


On Tuesday, 27 June 2017 at 09:54:19 UTC, John Burton wrote:
> I'm coming from a C++ background so I'm not too used to garbage 
> collection and it's implications. I have a function that 
> creates a std.socket.Socket using new and connects to a tcp 
> server, and writes some stuff to it. I then explicitly close 
> the socket, and the socket object goes out of scope.
>
> I assume that I do need to explicitly call close on the socket 
> as there is no deterministic destructor for class objects. I 
> further assume that the runtime will garbage collect any memory 
> allocated to the socket object at a later time.
>
> 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. from the documentation

>Immediately drop any connections and release socket resources. 
>Calling shutdown before close is recommended for 
>connection-oriented sockets. The Socket object is no longer 
>usable after close. Calling shutdown() before this is 
>recommended for connection-oriented sockets.

The GC (if you use it) will pick up the garbage for you.

> 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.

Have a look at automem (https://github.com/atilaneves/automem/)

>
> Am I doing this right? Or is there a better way to do this in D?
>
> Thanks.

There is also vibe.d if you are looking for more networking stuff.
https://github.com/rejectedsoftware/vibe.d

Best of luck
Nic



More information about the Digitalmars-d-learn mailing list