~= call copy ctor?

Jonathan M Davis jmdavisProg at gmx.com
Fri Jul 20 18:58:34 PDT 2012


On Saturday, July 21, 2012 00:04:21 Namespace wrote:
> > That happens because the destructor is being called when Garbage
> > collector is cleaning the memory used by the class instance.
> 
> How can i call the DTOR or at least a Release method after end of
> scope?
> Optimally automatic without any explicit calls.

You can use std.typecons.scoped, but then you can't pass the class around, 
which is exactly what would have happened with scoped. It's inherently unsafe.

You can do something like

MyObj obj = createObj();
scope(exit) clear(obj);

but again, it's going to be destroyed immediately when it leaves scope, and 
any reference to it which escapes will blow up when you use it. In neither 
case is there any reference counting.

You could use std.typecons.RefCounted, but unless _every_ instance of the 
object is wrapped in it (unfortunately, it uses alias this on its payload, 
making it easy to accidentally have references to its payload escape - which 
will be screwed up when the ref count reaches zero, and the payload is 
destroyed)

The reality of the matter is that if you want deterministic destruction, you 
should be using a struct, not a class. There are ways to force a class to be 
destroyed when it leaves scope, but they're inherently unsafe, so they should 
only be used if you really need them and know what you're doing. Classes are 
intended to live on the GC heap and be destroyed and freed by the GC when a 
garbage collection cycle finds that nothing refers to that object anymore.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list