【发布时间】:2014-09-13 18:00:18
【问题描述】:
我想用 myfree2() 替换名为 myfree() 的 free() 周围的包装函数的所有实例。不幸的是,我无法让它工作,因为第二个宏重新定义了第一个。如果第二个宏没有参数,为什么要重新定义第一个宏?
// I must delete this function or the macro will replace it as well and cause a syntax error!
void myfree(void *p)
{
if(p != NULL)
free(p);
}
void myfree2(void *p)
{
if(p != NULL)
free(p);
}
#define myfree(p) do { myfree2(p); p = (void *)0xdeadbeef; } while (0);
#define myfree myfree2
myfree(p); // Wrapper around free().
afunc(arg, myfree); // Wrapper is used as a function argument!
【问题讨论】:
-
#define myfree(p) do { myfree2(p); p = (void *)0xdeadbeef; } while (0)remove 分号或 funky do-while 没有意义。 PLUS:if(p != NULL) free(p);允许使用 NULL 参数调用 free。 -
请避免使用宏。它们是为了生活中的基本东西。其他任何你都躲在地狱里的东西
-
@EdHeal 我同意,但我认为在这种情况下这是非常值得的。