Manually allocating a File

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Feb 21 03:06:57 UTC 2018


On Wednesday, February 21, 2018 02:59:21 Nicholas Wilson via Digitalmars-d-
learn wrote:
> On Tuesday, 20 February 2018 at 15:32:45 UTC, Chris M. wrote:
> > Thanks for the info, that clears things up. Like I said, it was
> > more experimentation rather than me planning to actually use
> > it. Works now with the following modifications.
> >
> > import std.stdio;
> > import core.stdc.stdlib;
> > import std.conv;
> >
> > void main()
> > {
> >
> >     auto f = cast(File*) malloc(File.sizeof);
> >     emplace!File(f, "test.txt", "r");
> >     f.readln.write;
> >     free(f);
> >
> > }
> >
> >>>     (*f).readln.writeln;
> >>
> >> That * is unnecessary btw, in D you can
> >>
> >> f.readln
> >>
> >> and it will see it is a pointer to struct and dereference it
> >> for you.
> >
> > That's what I had originally, but I put the * in to see if it
> > would help with the original issue and never removed it
>
> FYI, File is a reference counted FILE* so theres not really any
> point of heap allocating it.

And worse, simply calling free does not run the File's destructor, so simply
using malloc to allocate it and free to free is not going to result in File
functioning properly. If someone were going to just use the C API and not
use std.stdio.File, then using malloc and free with FILE might make sense,
but it really doesn't make sense with File.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list