Deterministic resource freeing - delete deprecation (again)

Jacob Carlborg doob at me.com
Wed Apr 27 07:18:39 PDT 2011


On 2011-04-27 15:15, Steven Schveighoffer wrote:
> On Wed, 27 Apr 2011 07:42:22 -0400, Mariusz Gliwiński
> <alienballance at gmail.com> wrote:
>
>> Hello,
>> I'm next person, which isn't necessarily happy about delete operator
>> deprecation.
>> Because constructors / destructors are frequently used not only for
>> application controlled memory management, how would You implement
>> something like following code without delete operator?
>
> You can use clear to call the destructor of a class, and then GC.free
> (if you wish) to free the memory. The recommendation is to only use
> clear, and then let the GC clean up the memory at its leisure.
>
>>
>> <code>
>> void main(string[] args) {
>> auto res = new Resource();
>> auto s1 = new FirstSystem(res);
>> delete s1;
>> auto s2 = new SecondSystem(res);
>> }
>> class FirstSystem {
>> this(Resource res) {
>> res.referenced = true;
>> }
>> ~this() {
>> res.referenced=false;
>> }
>> }
>> class SecondSystem {
>> this(Resource res) {
>> assert(!res.referenced);
>> }
>> }
>> </code>
>
> Note there is a serious flaw in your destructor. Destructors cannot
> access GC managed memory because if the destructor is called inside the
> GC, the GC managed memory being referenced may have already been destroyed.
>
>> Next questions would be:
>> * Are you going to drop destructor as well, or maybe destructor is going
>> to be confusing feature with non-deterministic behaviour? (How would i
>> know when heap allocated Socket will be destructed -> when connection
>> will be closed -> if my system gonna be DoS'ed?)
>
> If the Socket closes its resources in the finalizer, then use clear().
> If the destructor does not close the resource (as could be the case if
> the resource is GC managed), you must implement a deterministic
> destructor member (with a different name, like close()) that you can
> call separately from the finalizer. There is no formal design for this,
> I really think there should be.

You mean like "dispose" in Tango. That's called when "delete" or "scope" 
is used.

>> * Are you going to stop supporting object oriented programming? (Well,
>> if *deterministic* resource managing can be only inside function, and
>> not object boundaries, that's my conclusion).
>
> I assume this is rhetorical.
>
> -Steve


-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list