dag@control.lth.se (Dag Bruck) (01/11/91)
In article <1991Jan10.223143.5752@Neon.Stanford.EDU> philip@pescadero.stanford.edu writes: >In article <7749@castle.ed.ac.uk>, eanv20@castle.ed.ac.uk (John Woods) writes: >|> Ahah. Could it be that only _named_ local objects may not be destructed before >|> they exit their scope? > >I tried your example on cfront 2.0, with similar results. Replacing > > Tracer("foo"); > >by Tracer a ("foo"); // the name a is not used anywhere else >also seemed to give the "expected" behaviour. > >I've seen a claim that this technique may also be used to implement a lock: > { Lock (lock_id); // Lock is a constructor: makes an object which > // locks the identified lock and remembers its identity > // critical region > } // destructor sees that unlock happens at close of scope I have recently posted on the use of lock objects (although the idea is not mine), so I will try to clear things up. Firstly, Lock (id); is an expression, not the declaration of an anonymous object. You convert the `id' to a lock, this conversions is an expression, and this expression is a complete statement (ending with `;'). So, when you get to the end of the statement, the compiler knows this expression is no longer needed, and destroys the result. Lock now(id); is the definition of an object `now' which is indeed guaranteed to exist until the end of the block where it is defined. >If the behaviour you report here is typical, this is clearly not a safe >alternative to > > lock(lock_id); > // critical region > unlock(lock_id); You're almost right, but probably not for the reason you thought! The problem is that the current language definition does not say when temporaries generated by the compiler are created and destroyed. Using Cfront 2.1, the use of explicit lock/unlock statements is not safe, because temporaries are destroyed after the last statement (i.e., after unlock). The use of Lock objects happens to work in Cfront, but that is just a lucky coincident until the C++ language definition becomes explicit about this. Dag M. Bruck