c语言-智能指针的用法
liaocj
2023-11-01 18:21:45
G_DEFINE_AUTOPTR_CLEANUP_FUNC 智能指针的用法
上代码:
#include <glib.h>
#include <stdio.h>
typedef struct {
int data;
} MyObject;
MyObject* my_object_new(int data) {
MyObject* obj = g_new(MyObject, 1);
obj->data = data;
return obj;
}
void my_object_free(MyObject* obj) {
if (!obj) {
return;
}
printf("Cleaning up MyObject with data: %d\n", obj->data);
g_free(obj);
}
G_DEFINE_AUTOPTR_CLEANUP_FUNC(MyObject, my_object_free)
void use_my_object() {
g_autoptr(MyObject) obj = my_object_new(42);
printf("MyObject data inside function: %d\n", obj->data);
}
int main(int argc, char *argv[]) {
use_my_object();
printf("Returned from use_my_object\n");
return 0;
}
编译:
gcc -o my_program my_program.c `pkg-config --cflags --libs glib-2.0`
运行结果
[root@localhost test]
MyObject data inside function: 42
Cleaning up MyObject with data: 42
Returned from use_my_object