在C中如何实现C++中smart pointer的部分功能,即当变量离开它作用域时自动destroy/free?在Linux下,可以使用gcc的扩展__attribute__ ((cleanup(xxx))) 。
举例,
#define local_type __attribute__ ((cleanup(my_free)))
static void my_free(void* pmem)
{
void** ppmem = (void**) pmem;
free(*ppmem);
}
int foo(void)
{
local_type int* p = (int*) malloc(sizeof(int));
//
// use *p
// when return, the memory block pointed by p is freed automatically
return 0;
}
举例,
#define local_type __attribute__ ((cleanup(my_free)))
static void my_free(void* pmem)
{
void** ppmem = (void**) pmem;
free(*ppmem);
}
int foo(void)
{
local_type int* p = (int*) malloc(sizeof(int));
//
// use *p
// when return, the memory block pointed by p is freed automatically
return 0;
}