1 // just docs: Memory management 2 /++ 3 Godot classes can be instanced with the engine's $(D memnew) template function. Other allocation methods such as D's GC $(D new) will not work with Godot classes, since the C++ engine is often responsible for deleting the objects. 4 5 After being created with $(D memnew), most Godot objects are managed automatically: 6 $(UL 7 $(LI $(D Node)s delete all their child nodes when they are themselves destroyed. Since nodes are usually children of a single large node tree, the $(D SceneTree), it is rarely necessary to manually delete them. 8 $(UL 9 $(LI If the node is not part of the tree or was removed with $(D Node.removeChild), delete it with $(D memdelete).) 10 $(LI To manually delete a node that is still in the tree, call $(D Node.queueFree) on it instead of $(D memdelete). This will remove and delete the node only after notifications and signals from the current frame have reached it.) 11 ) 12 ) 13 $(LI $(D Reference)s, including $(D Resource)s, are reference-counted with the $(D Ref!T) wrapper. 14 $(UL 15 $(LI $(D memnew) and functions returning References always return them already wrapped in Ref.) 16 $(LI Never manually delete a Reference with $(D memdelete); there may be other references to it elsewhere.) 17 $(LI Only pass around a raw pointer taken from a Ref if you can ensure that at least one Ref to it will exist for as long as the pointer does. This will be enforced with $(D scope) in $(D @safe) code once DIP1000 is accepted.) 18 $(LI Like Ref, $(D Variant) also adds to the ref-count when a Reference is assigned to it.) 19 ) 20 ) 21 ) 22 23 Examples: 24 --- 25 class Test : GodotScript!Node 26 { 27 @Method _ready() 28 { 29 Node a = memnew!Node; 30 Node b = memnew!Node; 31 a.addChild(b); 32 memdelete(a); // MUST manually delete nodes that aren't in the tree 33 // deleting the parent `a` also first deletes `b` 34 35 Node c = memnew!Node; 36 owner.addChild(c); // add `c` to the tree as a child of `this` 37 // the tree will delete `c` right before it deletes `this` when the game is exited 38 39 Node d = memnew!Node; 40 owner.addChild(d); 41 d.queueFree(); // remove and delete `d` once notifications and signals are finished being sent to it 42 43 Ref!ArrayMesh mesh = memnew!ArrayMesh; 44 // Ref will delete `mesh` at end of scope 45 46 Ref!Texture tex = ResourceLoader.load("res://icon.png").as!Texture; 47 // Ref will delete `tex` only if it isn't already loaded elsewhere. 48 49 GodotObject manuallyManaged = memnew!GodotObject; 50 memdelete(manuallyManaged); // MUST manually delete plain GodotObjects 51 } 52 } 53 --- 54 55 +/ 56 module godot.docs.memorymanagement;