How to use WeakRef in GDExtension to solve reference counting cycle

Godot Version

4.7-stable

Question

I want to resolve a reference counting cycle and I read about godots WeakRef for solving that, but I can’t find documentation on how to use godot::WeakRef in C++/GDExtension or even which header to include.

More detailed problem description

I have a class A which is passed to GDScript as a Ref<A>.
A holds a strong godot reference (Ref<B>) to another class B.
In B I also want to have a way to access A, so I want to use a WeakRef which is possible in GDScript but I couldn’t find a way to do the same in GDExtension. Or should I just use normal pointer and trust that Ref<A> will set that pointer to nullptr when the reference count hits 0?

This is the GDScript WeakRef, but how do I do the same thing in GDExtension, or should I just use a normal pointer?

class A : public RefCounted {
   GDCLASS(A, RefCounted)

private:
   Ref<B> m_b; // Strong Ref
}


class B : public RefCounted {
   GDClASS(B, RefCounted)

private:
   WeakRef m_a; // Weak Ref to not create a cycle

public:
   void setup(Ref<A> p_a); // puts Ref<A> into m_a without increasing the reference count

}

How would I do that and which header do I need to include :white_question_mark: I would be grateful for help :slight_smile:

Any good..?

cppreference.com : weakref…

What do you mean by that and why do you need to do it?

Ah sry, no, because I am using godot::Ref instead of standard library shared pointers.
But maybe I should switch to standard library shared pointers pointers instead of using godots Ref in member variables of my classes.
I didn’t want to do that because these classes are GDScript exposed and I wanted to keep everything in tidy godot:: types, but on the other hand member vars aren’t actually exposed only the getter and setter functions are, so I could use shared pointers right?

I edited my question to hopefully make my intent clearer!

If this is held internally (i.e. not made visible to script) you can get away with a naked pointer or manually managing the reference count of the Ref object.

The WeakRef header should be at: /godot-cpp/gen/include/godot_cpp/classes

I was also thinking about decrementing the reference count manually.. maybe I should try both approaches. I am a little bit afraid of creating a dangling pointer that only appears in esoteric circumstances, thats why I wanted to stick with godot types.

I’ll have a try and report :slight_smile: Thanks for your answer!

It’s dangling only if you let it dangle :smiley:
If you opt to managing a reference count manually - that’s almost the same as using a naked pointer.