Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!uwm.edu!spool.mu.edu!munnari.oz.au!comp.vuw.ac.nz!cc-server4.massey.ac.nz!S.J.Lovatt From: S.J.Lovatt@massey.ac.nz (S.J. Lovatt) Newsgroups: comp.lang.modula2 Subject: Re: How to write NEW? Keywords: NEW, DISPOSE Message-ID: <1991Apr21.005506.24764@massey.ac.nz> Date: 21 Apr 91 00:55:06 GMT References: <5122672@janhh.hanse.de> Organization: Massey University, Palmerston North, New Zealand Lines: 54 X-Reader: NETNEWS/PC Version 2.2 From: jan@janhh.hanse.de (Jan Willamowius) > > It looks like Wirth is using different ways to allocate memory > in different versions of his books. Sometimes he uses > 'Allocate(Var,SIZE(Type)' and sometimes 'NEW(Var)'. > > I like the second way better, but my compiler only supports Allocate. > So, is there a way to write a NEW (and DISPOSE, of course) ? < Code omitted > > PROCEDURE NEW(VAR p : ADDRESS); > BEGIN > Allocate(p,SIZE(p^)); > END NEW; > > The problem is that p 'looses' its type in the conversion to ADDRESS and > only a WORD is Allocated (ADDRESS is POINTER TO WORD). > > Any ideas ? Unfortunately, it is impossible to write NEW in Modula-2. One of the reasons I prefer Modula-2 over Pascal (for instance) is that almost all of the Modula-2's library procedures can be written in Modula-2. The exceptions which now remain are things like VAL, INC etc which translate directly into inline code on many compilers anyway. If I desperately wanted to do NEW, DISPOSE, etc, I would tack a macro processor on the front of my Modula-2 compiler (eg a C preprocessor) and define NEW as a macro which expands to 'Allocate (p,SIZE(p^))', thus not losing the size of p^. Modula-2 purists may feel free to cringe. Actually, I don't usually do this when programming in Modula-2 as I'd have to give up my integrated environment, although I do it a lot when programming in Fortran on Unix systems. What I sometimes do if I am doing a lot of allocating and deallocating is something like this: TYPE WidgetPtr = POINTER TO Widget; Widget = RECORD ...... END; PROCEDURE NEWWidget (VAR p : WidgetPtr); BEGIN Allocate (p,SIZE(p^)); END NEWWidget; If your compiler supports inline procedures, this is equivalent to the macro solution in space and time efficiency, while still being type-safe. - Simon -- Simon Lovatt | S.J.Lovatt@massey.ac.nz | Dept of Biotechnology | | Massey University, N.Z. | |