Proper way to work around `Invalid memory operation`?
Kapps via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Sep 27 06:45:32 PDT 2016
On Sunday, 25 September 2016 at 16:07:12 UTC, Matthias Klumpp
wrote:
> Hello!
>
> I have a class similar to this one:
> ```
> class Dummy
> {
>
> private:
>
> string tmpDir;
>
> public:
>
> this (string fname)
> {
> tmpDir = buildPath ("/tmp", fname.baseName);
> std.file.mkdirRecurse (tmpDir);
> }
>
> ~this ()
> {
> close ();
> }
>
> void close ()
> {
> if (std.file.exists (tmpDir))
> std.file.rmdirRecurse (tmpDir);
> }
> }
> ```
>
> When the GC calls the classes destructor, I get a
> `core.exception.InvalidMemoryOperationError@/<...>/ldc/runtime/druntime/src/core/exception.d(693): Invalid memory operation`
>
> Looks like rmdirRecurse tries to allocate with the GC, and the
> GC doesn't like that.
> Is there any good way to get the temporary directory deletet
> automatically when the object is freed?
> At time, I work around this bug by calling close() manually at
> the appropriate time, but this feel like a rather poor solution.
>
> Cheers,
> Matthias
As seen, you can't make GC allocations in dtors. And you should
never rely on the GC calling your dtor to close things like file
handles anyways. Consider making Dummy a struct and maybe using
std.typecons(?).RefCounted with it.
More information about the Digitalmars-d-learn
mailing list