Is there some way to implement a destructor for a ref object (as opposed to object) type? Compiling the code:
type ARef = ref object
name: string
proc `=destroy`(x: ARef) =
echo "Destroying A named ", x.name
`=destroy`(x.name)
gives the following error:
Error: signature for '=destroy' must be proc[T: object](x: var T) or proc[T: object](x: T)
This seems to work:
type
ARefObj = object
name: string
Aref = ref ARefObj
proc `=destroy`(x: ARefObj) =
echo "Destroying A named ", x.name
`=destroy`(x.name)
proc foo() =
var ff = Aref(name: "My Name")
foo()
if you dont care about looks
proc `=destroy`(x: typeof ARef()[]) =
Thanks @enthus1ast, what you suggest is precisely how I would do it if I was coding from scratch. However, I'm working with an existing code base that has a whole pile of ref object declarations. I was hoping to avoid the effort of converting them all to that form.
@SolitudeSF, your suggestion is exactly what I've been looking for! Thanks!!!
For completeness, here is how the destructor for a ref object subtype would be coded:
type ARef = ref object of RootRef
aname: string
proc `=destroy`(x: typeof ARef()[]) =
`=destroy`(x.aname)
type BRef = ref object of ARef
bname: string
proc `=destroy`(x: typeof BRef()[]) =
`=destroy`(x.bname)
`=destroy`((typeof ARef()[])(x)) # This is how the base type's destructor is called