Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
exception safety / RAII ?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Stefan Monnier <monnier@i...>
Subject: Re: exception safety / RAII ?
> My statements were based on the incorrect assumption that the OCaml GC
> closes files when it collects file handles. As this is not the case,
> I definitely agree with you that not explicitly closing files in OCaml is
> sloppy coding because they will not be closed implicitly.

My argument stays the same either way.

> However, provided you don't need to make any guarantees about when the
> file is  closed during the running of the program, I still think that
> implicitly  closing a file (or deallocating an external resource) via the
> GC is not  sloppy coding. Indeed, this facility can be very useful and can
> eliminate an important class of run-time errors.

Can you give examples where it's useful?  I don't consider "not needing to
call `close' on line NNNN of my code" to be useful.

Can you describe the "important class of runtime errors" that would be
supposedly eliminated?

>> This logic is routinely used in C to simply never call `free' because they
>> only run for a short time.  That's a textbook example of "sloppy coding".
> I wouldn't advocate never calling free() in a C program, but what is the
> difference between calling free at some unspecified point in the future and
> relying on a GC?

When you rely on a GC, you don't need to keep the pointer around somewhere
in order to be able to call "free" on it and you don't have to keep track of
who might still be using the object.  This means that a library for
a collection data structure can have a very different interface since it
doesn't have to worry about ownership of the contents of the
data structure.

>> It's extremely rare that the point in the code where a file can be closed
>> is not trivial to find.
> In the case of files, yes.  More generally, this can be applied to all
> sorts of external resources where that is not true.

Might be: there's no way we can generalize.  I'm talking about files here.
Finalizers are great, but they shouldn't be used for files.

I'd also argue that they generally shouldn't be used for any "external
resource".  Though I wouldn't be surprised if there's a counter example
somewhere where I'd agree that finalizers are good solution for the
management of some particular kind of external resource in some
particular circumstance.