Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!yale!mintaka!bloom-beacon!eru!hagbard!sunic!lth.se!newsuser From: dag@control.lth.se (Dag Bruck) Newsgroups: comp.std.c++ Subject: Re: Order of destructor calls for auto objects Summary: Order of destruction can be essential Message-ID: <1990Dec20.074232.9416@lth.se> Date: 20 Dec 90 07:42:32 GMT References: <1990Dec14.221247.9487@lia> Sender: newsuser@lth.se (LTH network news server) Organization: Department of Automatic Control, Lund, Sweden Lines: 58 In article martino@logitek.co.uk (Martin O'Nions) writes: > >P.S. is there really a case where there it is essential that one knows >the order of destruction, or is it just a case of planning inter-object >references in an appropriate way - this is NOT a flame, just a query. Yes, order of destruction can be essential in some applications. In "Exception Handling for C++," Koenig and Stroustrup describe the object-as-resource-allocator technique (Proc. C++ at Work, 1989). class Resource { .... }; class Lock { public: Lock(Resource& r) : res(r) { res.allocate(); } ~Lock() { res.free(); } private: Resource& res; }; The idea is that creating a Lock object allocates some resource, which is then freed when the Lock object is destroyed. void f(Resource& x) { Lock now(x); x.manipulate(); int& i = x.data; // .... } The Lock object `now' is destroyed when leaving function f, like any other local variable, so `x' is automatically freed. The beauty is that this technique works even if we get an exception somewhere. Another advantage is that you cannot forget to free a locked resource, because you don't have to write the call explicitly. The integer reference `i' clearly depends on `x' being locked, so here is an example where I want objects to be destroyed in reverse order of construction. This is of course a trivial example, but it is not difficult to imagine a case where the locking property is essential. A related problem is when temporary objects are destroyed. In many cases the compiler may create temporary objects, and the user has no control of when the temporaries are created or destroyed. Unfortunately, the current language definition does not give any constraints at all. Using Cfront, I discovered that the approach above worked in a particular case, but the "equivalent" code without using a Lock object did not. The C++ standardization committee has noted this problem, and will surely resolve the issue. Dag M. Bruck -- Department of Automatic Control E-mail: dag@control.lth.se Lund Institute of Technology P. O. Box 118 Phone: +46 46-104287 S-221 00 Lund, SWEDEN Fax: +46 46-138118