Destructor semantics

Don nospam at nospam.com
Wed Aug 11 13:14:56 PDT 2010


Michel Fortin wrote:
> On 2010-08-11 15:09:45 -0400, Jonathan M Davis <jmdavisprog at gmail.com> 
> said:
> 
>> On Wednesday, August 11, 2010 11:33:54 Michel Fortin wrote:
>>> I'm not too sure that'll work very well. I think a better solution
>>> would be to have a way to distinguish between a struct that can be put
>>> on the GC heap and one that cannot. A struct that cannot go on the GC
>>> heap make it safe to access GC-managed members in its destructor, and
>>> thus can have a @safe destructor.
>>
>> But couldn't the fact that a struct has a destructor make it so that 
>> it can't be
>> declared anywhere but on the heap? The destructor itself could be what
>> distinguishes them. I don't see a need for any other @attributes or 
>> whatnot to
>> distinguish them.
> 
> Sure, and now you can't use std.containers.Array as a member in a Class, 
> neither std.stdio.File, etc. Is there something left classes can do?

As far as I can tell, the use cases for finalizers are very limited. To 
me, destructors don't make any sense unless they are deterministic.
For example, I think having a File class is probably a bug. You may be 
on a system which has no limit on the number of file handles, but 
generally, if you need resource management, you need a guarantee that 
the destructor will be called.

If a file handle is stored as part of a class, with a destructor that 
closes the file, the file might never get closed. So I don't think it's 
unreasonable to say that a struct with a destructor cannot be a member 
of a class.

Personally I think destructors should be restricted to structs and scope 
classes. I suspect that some form of registration with the gc could do 
the job of finalizers.

Destructor <=> deterministic destruction.


More information about the Digitalmars-d mailing list