参考 https://snai.pe/c/c-smart-pointers/
attribute ((cleanup(f)): 用于动态分配对象的自动释放,cleanup修饰一个变量在该变量作用域结束后, 自动调用一个指定的方法 f 。所谓作用域结束,包括大括号结束、return、goto、break、exception等各种情况。
下面是实现方法:
#define autofree __attribute__((cleanup(free_stack)))
__attribute__ ((always_inline))
inline void free_stack(void *ptr) {
free(*(void **) ptr);
}
int main(void) {
autofree int *i = malloc(sizeof (int));
*i = 1;
return *i;
}