Lifetime of godot-cpp node pointers?

Godot Version

4.3

Question

I was wondering what is the lifetime of Node pointers (so Node*) that I get after calling get_node in C++ using godot-cpp?

I get that nodes themselves are owned by the scene / their parent node and are released from Godot when they are removed from the tree (or rather when their refcount reaches 0?). I can use the instance ID to check if the node is still valid.

But what about the pointer that I get? If I look at Wrapped I can see a single stored property GodotObject *_owner which is the pointer to the wrapped Godot object, surely this must be allocated somewhere when I call get_node?

I ask because for my game I need to store node pointers for later use (or “escape” them from the Godot scope as I like to call it). How do I know if the pointer that I’m storing is still valid? And how are they released anyway in regular godot-cpp use, assuming I never store them outside of local functions?

Thanks!

Nodes aren’t ref counted so you are in charge of managing them.

When you memdelete() a Node it will emit the Object.NOTIFICATION_PREDELETE notification() where it will memdelete() its children and clean up before deleting itself here godot/scene/main/node.cpp at master · godotengine/godot · GitHub

1 Like

Does this apply to godot-cpp / GDExtension though? I couldn’t find any documentation on memory management for godot-cpp, memnew and memdelete both seem to be Godot internals, too low level for me

Yes, you can use memnew() and memdelete() from godot-cpp which does that.

1 Like

In the GDExtension C++ example page, there are no mentions of memdelete at all, is this an omission then?

Edit: to be clear, I’m not talking about storing nodes that I allocate myself (in which case I would use memnew / memdelete), I’m talking about storing nodes retrieved using get_node

Same precedent, not refcounted. Only deleted if it’s been explicitly freed/deleted. Just like queue_free in gdscript (and GDExtension)