Apologies if this question is fairly obvious, but I wasn't able to clear this up with the documentation. Anyway, I'm curious as to what happens to reference counted objects which only live on the stack. Here is a simple example program:
proc test() =
var a = readFile("test.nim")
var b = readFile("test.nim")
echo a
test()
The test() function looks like this in the generated C file:
N_NIMCALL(void, test_69002)(void) {
NimStringDesc* a;
NimStringDesc* b;
nimfr("test", "test.nim")
nimln(2, "test.nim");
a = readfile_7680(((NimStringDesc*) &TMP121));
nimln(3, "test.nim");
b = readfile_7680(((NimStringDesc*) &TMP121));
nimln(4, "test.nim");
printf("%s\015\012", (a)->data);
popFrame();
}
Here is where my confusion stems from. The readFile() function appears to create a new string, which in turn seems to create a new reference counted object with the reference count set to zero. What I don't understand is, what prevents the GC from coming along and potentially collecting this object before the end of the proc? Presumably it could be invoked on when the second readFile() call is made.
Thanks for any insight.
Great, thanks for that.
Just as a follow up question. What is the best way to clean up an object that is assigned to a ref on the stack? Will it become available for GC collection as soon as I assign nil to the ref? Does anything else need to be done or is there a more idiomatic way to deal with it? Cheers.