godotengine / godot

Godot Engine – Multi-platform 2D and 3D game engine
https://godotengine.org
MIT License
89.03k stars 20.19k forks source link

Memory leak on custom classes #95534

Closed ryi3r closed 1 month ago

ryi3r commented 1 month ago

Tested versions

v4.3.rc3.official [03afb92ef]

System information

Godot v4.3.rc3 - Windows 10.0.22631 - Vulkan (Forward+) - dedicated NVIDIA GeForce RTX 3050 Laptop GPU (NVIDIA; 32.0.15.6081) - AMD Ryzen 7 5800H with Radeon Graphics (16 Threads)

Issue description

Custom classes are leaking memory, whenever it goes out of scope, or it has 0 references, or a custom class references another class. Custom classes referencing other classes also are not releasing their memory if you manually free them up. Expected behaviour is to not leak any kind of memory.

Steps to reproduce

Minimal reproduction project (MRP)

GodotMemoryLeak.zip

huwpascoe commented 1 month ago

By default custom classes extend RefCounted

class_name MyRefClass
# extends RefCounted

And they will free() automatically when out of scope.

For member variables that extend Object, NOTIFICATION_PREDELETE is the place to free()

var variable := MyClass.new() # needs to manually free()
var variable2 := MyRefClass.new() # will free automatically

func _notification(what: int) -> void:
    if what == NOTIFICATION_PREDELETE:
        variable.free()