TDPL: Manual invocation of destructor

Lutger lutger.blijdestijn at gmail.com
Mon Aug 9 15:09:59 PDT 2010


Max Samukha wrote:

> On 08/09/2010 03:40 PM, Steven Schveighoffer wrote:
>> On Mon, 09 Aug 2010 08:28:38 -0400, Andrej Mitrovic
>> <andrej.mitrovich at gmail.com> wrote:
>>
>>> It's rather perplexing, isn't it? It states in TDPL:
>>>
>>> "After you invoke clear, the object is still alive and well, but its
>>> destructor has been called and the object is now carrying its
>>> default-constructed stated. During the next garbage collection, the
>>> destructor is called again, because the garbage collector has no idea in
>>> what state you have left the object."
>>
>> This seems totally wrong, what if an object has no default constructor?
>> The spec used to say (maybe it still does) that a destructor is
>> guaranteed to only ever be called once.
>>
>> I honestly thought the point of clear was to simply leave the memory in
>> place as a kind of "zombie" object until the GC could collect it, to
>> avoid having the block get recycled into a new object, and then use an
>> old reference to it (via delete). I didn't know someone would ever
>> purposefully use it. What is the point of calling clear then, if clear
>> doesn't get rid of the object and leave it uninitialized?
>>
>>> But in what situation would you want to manipulate an object that was
>>> already cleared and ready for garbage collection?
>>
>> None. That's the point. clear is saying "I don't want to use this object
>> any more". The runtime (I thought) was just being conservative and
>> leaving the memory in place until it could verify there were no other
>> pointers to it.
>>
>> I'm starting to climb the fence into the "leave delete in the language"
>> camp...
>>
>> -Steve
> 
> I agree. The whole purpose of clearing a GC-allocated object is
> deterministically freeing the resources the object may have acquired.
> Otherwise, it could as well be left alive until the next garbage
> collection cycle. Reconstructing the object is not a good idea since the
> object may, for example, acquire an expensive resource in its
> constructor etc.
> 
> FWIW, C# solved the problem years ago by separating the destructor
> (IDisposable.Dispose) from finalizer. Let's learn something from it.

IDisposable has quite a few problems and gotcha's of its own:

http://www.codeproject.com/KB/dotnet/idisposable.aspx 

Especially these:
- Finalizers are called if constructors throw an exception
- Microsoft recommends that every type implementing IDisposable will check in 
every method and property accessor to see if it has been disposed, and throw an 
exception if it has


More information about the Digitalmars-d mailing list