On 1/26/16 4:23 PM, Igor wrote:
On Tuesday, 26 January 2016 at 20:17:20 UTC, Steven Schveighoffer wrote:
On 1/26/16 9:20 AM, Igor wrote:
I have successfully malloc'ed an object but when I go to free it in the
destructor I get an exception. The destructor simply has

~this() // destructor for Foo
{
     core.stdc.stdlib.free(&this);
}


auto buffer = core.stdc.stdlib.malloc(__traits(classInstanceSize,
App))[0..__traits(classInstanceSize, App)];
auto app = cast(App)emplace!App(buffer[]);

I tried to retain a ptr to buffer and free that but still no good. I
also get a depreciation warning that &this is not an lvalue. Hopefully I
don't have to keep a ptr around to this simply to free it and avoid
future issues?

So how am I suppose to free an object?

Don't do it in the destructor.

I can only imagine that you are triggering the destructor with
destroy? In this case, destroy is calling the destructor, but then
tries to zero the memory (which has already been freed).

There is a mechanism D supports (but I believe is deprecated) by
overriding new and delete. You may want to try that. It's deprecated,
but has been for years and years, and I doubt it's going away any time
soon.

A class shouldn't care how it's allocated or destroyed. That is for
the memory manager to worry about.

um? Memory manager? I am doing it manually C++ style so I don't have to
worry about the god forsaken memory manager. Why is it so difficult? I
create the object and release it when I need to.

As Mike said, I mean whatever you are using for memory management. The class is not responsible for allocating or deallocating itself, just initializing itself and deinitializing itself.

So if you use malloc and free, that is your memory manager.


I can replace the destroy(f) with free(inline the code) but I don't see
why that should matter. The whole point of destructors is to do this
sort of stuff. That's why they were invented in the first place!?!

It isn't even this way in C++. No destructors deallocate 'this'.

All D destructors should destroy all the members. And generally speaking, if you ever plan to use a class with the GC, you should only destroy non-GC members. The GC members may already be destroyed.

-Steve

Reply via email to