From the documentation of GLib.DateTime, I read that when I get a new DateTime object, I should release it with its method unref when I’m done with it.
So why when running the following test.js program, almost every time ten seconds after its launch I get the error g_date_time_unref: assertion 'datetime->ref_count > 0' failed ? Removing the unref call prevents the issue.
// test.js
const GLib = imports.gi.GLib;
const Mainloop = imports.mainloop;
class Hour_of_now {
constructor() {
const now = GLib.DateTime.new_now_local();
this.hour = now.get_hour();
now.unref(); // I'm done with it, so release it.
}
get() { return this.hour; }
}
const hour = new Hour_of_now();
log(hour.get());
Mainloop.run();
Because the JS API reference is generated from the C API reference, where reference counting is manual.
Because once the last reference to something is released, the underlying C memory is freed, and any subsequent access is a use-after-free, which could crash your application, self-destruct your computer, or cause vacuum decay in the local bubble of space time.
The general rule is: do not overthink it, and don’t do manual memory management. In other words:
Most developers will never have to worry about GObject referencing or memory leaks, especially if writing clean, uncomplicated code.