__attribute__ ((cleanup(xxx))) -- gcc extension

来源:互联网 发布:兄弟连php pdf 编辑:程序博客网 时间:2024/05/13 14:14
在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;
}
原创粉丝点击