clear() and UFCS
Jonathan M Davis
jmdavisProg at gmx.com
Fri May 25 19:27:15 PDT 2012
On Saturday, May 26, 2012 04:04:51 Mehrdad wrote:
> Would you mind explaining the difference between clear(), delete,
> and __dtor/etc? I think it's a little confusing for me.
clear destroys the object (by calling its finalizer or destructor) and then in
the case of classes, it zeroes out its vtable so that if you accidentally the
object after clearing it, it'll blow up rather than getting weird, non-
deterministic behavior. In the case of structs, I think that it puts the
object in its init state, but I'm not sure.
clear does _not_ free the object's memory. It merely destroys the object so
that whatever other resources it references can be released (or just
unreferenced in the case of GC heap allocated objects that it references).
delete does what it does in C++. It destroys the object and then frees the
memory. It was decided that having a language construct which freed memory on
the GC heap was too dangerous and error-prone and shouldn't be encouraged, so
it's being removed. It's still quite possible however, to create a function
which destroys and object and then tells the GC to free that object's memory
using the stuff in core.memory.
__dtor is simply the object's destructor. Calling it calls that function.
However, I don't believe that it destroys what the object references (since
that would require doing more than simply calling the destructor). As I
recall, you have to do something else which is a bit involved to do that.
There was a discussion on it recently, but I don't recall the details
unfortunately.
In the long run, I expect that anyone who really wants to use something akin
to delete will likely use custom allocators (e.g. using malloc and free)
rather than using the GC heap, possibly with some sort of ref-counting. So,
you'd get something like
//non-ref-counted
auto a = ca.allocate!MyClass(args);
ca.deallocate(a);
or
//ref-counted
{
auto a = ca.allocate!MyClass(args);
}
//a has left scope, so its ref-count reach zero, and it was destroyed
Obviously we don't have the custom allocator stuff fully ironed out yet though.
Andrei has been working on those, but he's been a bit swamped, so who knows
when we'll see them.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list