Most of my work for the last few years have been fairly high-level with Nim. I've never really needed to truly learn anything low-level like dealing with pointer or ptr T or being so heavily involved with C libraries, etc.
For the last couple of months though I've been learning graphics programming and made my first steps creating a graphics library (like threejs / raylib) using the new SDL3 GPU API.
There are things I want to be able to do now, like free SDL resources automatically when it goes out of scope via =destroy hooks.
That's pretty straightforward to do but what about my own custom object types the have these resources as properties? Do I have to create that hook for the object too or no? What about custom object types that have pointer or ptr T properties? Are they managed automatically by Nim or should I create hooks for these?
I don't even know if my questions are properly worded this is new to me. I've read https://nim-lang.org/docs/destructors.html but it's thin in the content department as far as when it should be used and how. At least for someone that doesn't already understand these concepts.
I've been working with ChatGPT to understand some of the concepts but it's hard to trust it when I can't verify because there's no documentation aside from what I've mentioned (at least it's all I've been able to find).
I guess my actual question is can someone help me understand in what cases these destructor hooks should be created, and any 'gotchas' for working with pointers or ptr T's as it relates to custom object types?
A toy example:
type
Material = object of RootObj
vShader: GPUShaderThing # is SDL type w/ 'releaseGPUShaderThing' destructor
fShader: GPUShaderTHing
someData: pointer
someMoreData: ptr SomeOtherObjectType
x,y,z: float32
How would this be handled? Do I only need to create a destructor for the GPUShaderThing (adding the releaseGPUShaderThing function call)? Or do I need to free each property? Something else?
Thank you for your time.
In addition to ElegantBeefs response, you can make a custom destroy for Material and free the SomeMoreData pointer there. That works when Material owns the someMoreData pointer. Just be sure to call destroy on all of the fields. With Beef’s approach you’d only need to worry about SomeOtherDataType’s destructor.
I’ve found it’s good to write some tests and destructors with a ‘when defined(debugXYZ): echo “destroying 123”‘. Just to help understand what’s going on. There’s definitely a few gotchas but nothing too complex.