Skip to content

Comment on Generalized Macrosparent

Comments

Macros: Dangers and Alternatives

here is a simple LispWorks program using macros to provide manual memory management:

  CL-USER 17 > (defresource rarray (size)
                 :constructor (make-array size)
                 :initial-copies 0)
  RARRAY
The above macro form defines a new manually managed resource named RARRAY. There is a constructor for allocating new RARRAY objects. Here the constructor just allocates an array of a certain size.
  CL-USER 18 > (using-resource (ra rarray 10)
                 (setf (aref ra 3) 10)
                 (incf (aref ra 3) 32)
                 (aref ra 3))
  42
The above USING-RESOURCE macro looks up an array of size 10 from the resource pool. If there is none, it allocates one. In the context of the macro form, the array is marked in the pool as used and provided to the code. Upon leaving the dynamic context of USING-RESOURCE, the array will be returned to the pool and marked as unused.

Bonus: DEFRESOURCE, USING-RESOURCE, SETF and INCF are all macros.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.