What does `g_autoptr(MyApplication) app = my_application_new();` mean


I was browsing through a flutter linux application source code and i hit a little snag understanding this method of declaration and if it’s C or C++.

// Source code for context 
#include "my_application.h"
int main(int argc, char** argv) {
  g_autoptr(MyApplication) app = my_application_new();
  return g_application_run(G_APPLICATION(app), argc, argv);

I’m familiar with these declaration and assigning methods

structB->hb = 16;
// OR
structB.hb = 18;
// OR
int hb = 10; 
// And the other common method of declaration 

But i have never seen this method of declaration and I really don’t know what it means

g_autoptr(MyApplication) app = my_application_new();

>Solution :

Here, g_autoptr is a macro that declares a pointer to the specified type and registers a function that will delete object when the pointer goes out of scope.

In GCC, g_autoptr produces something like

__attribute__((cleanup(MyApplication::cleanup_func))) MyApplication *app = my_application_new();

Using this extension, the compiler can automatically detect when the pointer is no longer used and call the function that will free the object.

Please see https://blogs.gnome.org/desrt/2015/01/30/g_autoptr/ for more examples.

Leave a Reply Cancel reply