Ah…I slowly understood how g_autoptr
works.
Out of scope is, yes, simply out of scope. Nothing difficult, as the document states.
What I wondered was what would be happened if we made a function, having a g_autoptr
-ed GSomething and returning it.
I understand functional programming seems inefficient from the C programming point of view, but anyway, the way is generating objects and discarding them, as a sort of chained sequence. That is why I was interested in what happens if a function returns g_autoptr
-ed GSomething.
I expected g_autoptr
with GSomething would help a sort of functional programming in the C language, but last time, no good examples popped up in my mind.
Here is a silly but simple example:
#include <glib-2.0/glib.h>
#include <stdio.h>
GString* number2string(gint z, gint radix) {
g_autoptr(GString) a = g_string_new("");
g_autoptr(GString) b = g_string_new("");
while (z != 0) {
g_string_printf(b, "%d", z % radix);
g_string_prepend(a, b->str);
z /= radix;
}
return a;
}
int main(void) {
gchar base[3];
scanf("%2s%*[^\n]", base);
getchar();
gchar num[20];
while (scanf("%19s%*[^\n]", num) != EOF) {
getchar();
g_print("%s\n", number2string(strtol(num, NULL, 10), strtol(base, NULL, 10))->str);
}
return EXIT_SUCCESS;
}
This code tries converting from a number in decimal, inputted from the terminal, to its binary one. The number2string
function, named after number->string
function of the Scheme language, has two g_autoptr
-ed GString
objects, where a
is finally returned but b
is not.
Now what happens? Nothing printed.
number2string
tries returning a GString
object, or a
, but miserably g_autoptr
discards what a
is because of “out of scope”. Simple.
Thus, if we want to make a GSomething returned, we should not make it sandwiched with g_autoptr
. That is gonna be a kind of “know-how”.
Anyway, this experiment makes me clear.
Thanks.