What's wrong with this GLib.DateTime.unref
method call? (original) (raw)
August 20, 2024, 2:52pm 1
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();
$ gjs --version
gjs 1.80.2
$ gjs test.js
Gjs-Message: 16:34:13.528: JS LOG: 16
(gjs:371836): GLib-CRITICAL **: 16:34:23.971: g_date_time_unref: assertion 'datetime->ref_count > 0' failed
pwithnall (Philip Withnall) August 20, 2024, 3:10pm 2
Memory management is automatic in JavaScript, you don’t need to manually unref most objects (although there are some exceptions — see the guide).
gihaume August 20, 2024, 3:31pm 3
Thanks.
- So why the
gjs
reference documentation I linked advises to do it ? - The
tips
guide you linked is not very explicit about it. The only maybe reference to this I can read is
Put simply, as long as GJS can trace a GObject to a variable, it will ensure the reference count does not drop to 0.
which doesn’t mean that a variables referencing the object having left its scope decrements the reference counter.
- Finally, why having called
unref
would be a critical error ? Why callingunref
too much would be a problem for memory management ?
ebassi (Emmanuele Bassi) August 20, 2024, 3:38pm 4
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.
pwithnall (Philip Withnall) August 22, 2024, 3:27pm 5
Be the chaos you want to see in the universe
system (system) Closed September 21, 2024, 3:28pm 6
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.