why std.stdio.File is a struct?

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Thu Oct 20 00:40:05 PDT 2016


On Thursday, October 20, 2016 06:59:12 lumpyzhu via Digitalmars-d wrote:
> std.stdio.File has reference counter inside,
> why not std.stdio.File is class?

By using a struct with a reference count, you get deterministic destruction,
and the file will be closed as soon as the reference count hits zero. If it
were a class, then it would only be closed when the GC happened to collect
the memory, and there's no guarantee that it will _ever_ collect the memory
(e.g. the GC normally only runs when you call new, so if you never allocate
memory again after allocating the File, then the GC will never collect it
even if nothing refers to it anymore).

User-defined types that manage system resources are pretty much always
better off as structs so that they can have deterministic destruction. Java
and C# have a terrible time with stuff like closing files, essentially
requiring you to do it manually, because there's no guarantee that the
finalizers for their file classes will ever run, and you risk the resource
never being released until the program terminates, which can be a big
problem. We'd have the same problem if we used a class for std.stdio.File,
whereas using a struct works great.

In general, in D, if you don't need inheritance and polymorphism, you
probably shouldn't be using a class.

- Jonathan M Davis



More information about the Digitalmars-d mailing list