Menu
CoddyTech

Reference Lifetimes

Lesson 40 of 48 in Coddy's GDScript for C Developers course.

C pointer assignment neither retains an allocation nor tracks its destruction. Clearing one alias leaves other aliases unchanged, but freeing through any owner makes all pointers to that storage unusable. Godot RefCounted references instead retain the object and release it when no strong references remain; cycles are not reclaimed automatically. WeakRef observes without retaining and can report that its target is gone. A raw C pointer is not a checked weak reference. The C example keeps its allocation live through observation and frees it exactly once afterward.

Complete C comparison. Save the listed files together and compile the .c files; main is the entry point.

C file item.h:

#ifndef ITEM_H
#define ITEM_H
struct Item { int value; };
#endif

C file main.c:

#include <stdio.h>
#include <stdlib.h>
#include "item.h"
int main(void) { struct Item *a=malloc(sizeof *a); if(!a) return 1; a->value=7; struct Item *observer=a,*b=a; a=NULL; puts(observer==b?"true":"false"); free(b); return 0; }

C output:

true

GDScript example file main.gd:

extends Node

func _ready() -> void:
	var a: RefCounted = RefCounted.new()
	var weak: WeakRef = weakref(a)
	var b: RefCounted = a
	a = null
	print(weak.get_ref() == b)

GDScript output:

true
challenge icon

Challenge

Easy

Implement OwnedNote(text:String) and static NoteViews.label(note:OwnedNote)->String. Return missing for null; otherwise return note.text. Solve creates a note for a string input, or passes null. Do not manually free RefCounted instances.

Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.

Your code goes in owned_note.gd, note_views.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.

Try it yourself

extends Node

func contract_ok(data: Array) -> bool:
	var original: OwnedNote = OwnedNote.new("a")
	var alias: OwnedNote = original
	original = null
	if NoteViews.label(alias) != "a" or NoteViews.label(null) != "missing": return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for C Developers

Practice on your own: Online GDScript compiler