is struct delete deterministic? (cf used in Unique)

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Mar 8 04:13:28 PDT 2015


On Saturday, March 07, 2015 17:20:49 Timothee Cour via Digitalmars-d-learn wrote:
> To clarify, I'm only asking about a struct allocated via new.
> Unique!T is wrapped around a struct, but it allocates a struct T via 'new',
> so my question still holds: does 'delete t' (where t is a struct allocated
> via new) guarantee deterministic destruction?
>
> I'm guessing yes, otherwise Unique would be broken, but where is that
> specified in the docs?
> And if delete is to be deprecated (according to the docs), what is the
> correct way to do that (despite fact that Unique relies on delete).

Yes, delete is deterministic. It's basically the same as what you get in C++
except that it's using the GC heap and therefore is not safe. delete is
supposed to have been deprecated but has not been yet (mostly because no one
has gotten around to doing it).

If you're using the GC heap and want to destroy an object, that's what
destroy is for - but it doesn't free the memory, because that's not safe.
You can free the memory with core.memory.GC.free, but you have to have
destroyed the object first, since free just frees memory. But that's just
duplicating what delete does, so it's still unsafe.

What's generally considered the correct way to deal with manual memory
management involves allocating using C's malloc, constructing via emplace,
and then using destroy and C's free to destroy the object and free its
memory when you're done. But that's way more of a pain then using new and
then delete, which is probably part of why some folks still use delete (in
the case of Unique though, I expect that it's just because it's been around
a while). Hopefully, the standard allocator stuff will make it as simple as
using new and delete though - e.g. something like

auto ptr = alloc.make!Myobj(arg1, arg2);
alloc.free(ptr);

but the standard allocator stuff isn't currently far enough along yet for us
to be at that point unfortunately.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list