From: Ludovic Brenta <ludovic@ludovic-brenta.org>
Subject: Re: How to properly clean up an extended, generic structure?
Date: Sun, 09 Jul 2006 16:33:43 +0200
Date: 2006-07-09T16:33:43+02:00 [thread overview]
Message-ID: <87wtamalvc.fsf@ludovic-brenta.org> (raw)
In-Reply-To: 44b107b7$0$3629$4d3efbfe@news.sover.net
Peter C. Chapin writes:
> Right now I'm working on a generic package that implements splay
> trees. My generic parameters look like:
>
> generic
> type Item_Type is private;
> with function "<"(L : Item_Type; R : Item_Type) return Boolean;
> package Splay_Tree is ...
>
>
> I've created a procedure Destroy_Tree that uses an instance of
> Ada.Unchecked_Deallocation to remove all the nodes in a given
> tree. Destroy_Tree is meant to be used when a tree is no longer needed
> and it serves the role of a destructor (using C++ terminology). It
> occurs to me, though, that Item_Type might have its own clean up
> needs. I assume that Unchecked_Deallocation knows nothing about
> that. Thus my code currently might be improperly cleaning up the
> Item_Types in each tree node. In C++ this is not a problem because
> deleting a node invokes the node's destructor (if there is one) so the
> issue is handled automatically. My question is how do I best deal with
> this in Ada?
>
> I could pass a clean up procedure for Item_Types as another generic
> parameter. However, in cases where no such procedure is necessary (for
> example, when Item_Type is just Integer), such a solution seems
> awkward. Is there a nicer solution?
You do not need to change anything to your Splay_Tree; instead, just
pass a controlled type as the Item_Type. A controlled type is a type
derived from Ada.Finalization.Controlled(*). You override its
Finalize procedure to reclaim the storage for the item; that's the
equivalent of a destructor in C++. The language guarantees (ARM
7.6(1)) that the instance of Unchecked_Deallocation will call your
Finalize, much like delete in C++ will call your destructor.
For more details, see ARM 7.6.
(*) or Limited_Controlled, but your generic does not accept limited
types, which is probably OK for a container.
HTH
--
Ludovic Brenta.
next prev parent reply other threads:[~2006-07-09 14:33 UTC|newest]
Thread overview: 8+ messages / expand[flat|nested] mbox.gz Atom feed top
2006-07-09 13:42 How to properly clean up an extended, generic structure? Peter C. Chapin
2006-07-09 14:29 ` jimmaureenrogers
2006-07-09 14:33 ` Ludovic Brenta [this message]
2006-07-09 16:21 ` Peter C. Chapin
2006-07-09 14:49 ` Björn Persson
2006-07-09 14:57 ` Georg Bauhaus
2006-07-09 19:46 ` Jeffrey R. Carter
2006-07-10 7:38 ` Jean-Pierre Rosen
replies disabled
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox