There is no standard predefined way to copy CLOS objects at all. If possible, itโs not at all trivial to provide a reasonable default copy operation that does the right thing (at least) most of the time for arbitrary objects, since the correct semantics vary from class to class and from application to application. The advanced features provided by MOPs make it even more difficult to provide this default value. In addition, in CL, which is a garbage collection language, copying objects really is not required very often, for example. when they are passed as parameters or returned. Thus, implementing your copy operations as needed is likely to be the cleanest solution.
As the saying goes, here is what I found in one of my snippet files that can do what you want:
(defun shallow-copy-object (original) (let* ((class (class-of original)) (copy (allocate-instance class))) (dolist (slot (mapcar #'slot-definition-name (class-slots class))) (when (slot-boundp original slot) (setf (slot-value copy slot) (slot-value original slot)))) copy))
You will need MOP support for class-slots
and slot-definition-name
.
(I probably took this from the old cll thread , but I donโt remember. I never needed something like this, so itโs completely untested.)
You can use it like this (verified using CCL):
CL-USER> (defclass foo () ((x :accessor x :initarg :x) (y :accessor y :initarg :y)))
source share