Godot 4.3
I’ve created a C++ extension and hope that a specific function can be called when the object is released.The code is as follows:
CRObject.hpp
using namespace godot;
class CRObject: public RefCounted{
GDCLASS(CRObject, RefCounted)
protected:
static void _bind_methods();
public:
CRObject();
~CRObject();
GDVIRTUAL0(_dealloc);
void dealloc();
};
CRObject.cpp
using namespace godot;
void CRObject::_bind_methods() {
UtilityFunctions::print("Bind methods");
ClassDB::bind_method(D_METHOD("dealloc"), &CRObject::dealloc);
GDVIRTUAL_BIND(_dealloc);
}
CRObject::CRObject() {
UtilityFunctions::print("Constructor");
}
CRObject::~CRObject() {
UtilityFunctions::print("Destructor");
dealloc();
}
void CRObject::dealloc(){
UtilityFunctions::print("dealloc");
if (GDVIRTUAL_CALL(_dealloc)){
UtilityFunctions::print("call");
} else {
UtilityFunctions::print("no call");
}
}
In the Godot editor, I created a subclass TestObj of CRObject. The code is as follows:
class_name TestObj
extends CRObject
func _dealloc():
print("GD dealloc");
Finally, I created a TestObj object in main.gd. However, the _dealloc method of TestObj was not called.
main.gd
func _ready() -> void:
var obj = TestObj.new()
pass # Replace with function body.
Console output:
Bind methods
Constructor
Destructor
dealloc
no call
--- Debugging process stopped ---
How should I modify my program to ensure that the _dealloc method of TestObj is called correctly?