why std.stdio.File is a struct?
lumpyzhu via Digitalmars-d
digitalmars-d at puremagic.com
Sat Oct 22 23:13:29 PDT 2016
On Thursday, 20 October 2016 at 07:40:05 UTC, Jonathan M Davis
wrote:
> 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
thanks..
but structs are copy by value,
In C++, I can use reference to avoid value-copy,
------------------------------------------
class MyClass {....};
void myFunc(const MyClass& a, MyClass& b) {...};
{
MyClass object;
myFunc(object);
// f will destroyed here.
}
------------------------------------------
in c++, I know where the object is destroyed..
but how to convert this c++ code to d?
More information about the Digitalmars-d
mailing list