我知道用空指针调用
free
是一个 NO-OP,free
已经对此进行了检查,但 free
也是一个 libc
库函数,可能有一些固定的开销方面什么都不做。
我的问题是,是否值得考虑更换这个:
delete ptr;
靠这个?
if (ptr)
delete ptr;
首先,在将呼叫转接至
delete
之前,free
是否会进行空检查?或者 delete
通常会以绝对透明的方式转接电话吗?
如果是这样的话,我们从现在开始就可以用
free
来说话了。
那么,为了避免潜在昂贵的
free
执行而不执行任何操作,上述转换是否值得?在 C++ 中,这可能是一个需要考虑的事情,因为在到达最终目的地时,周围的物体可能会留下一堆空物体;其析构函数将使用空指针调用 std::move
的对象。检查free
源代码,我发现了这个:
glibc
这么称呼它看起来根本不“免费”;下面有一些东西,甚至在空检查之前还有一个
void
free (void *ptr)
{
struct header *real;
/* Determine real implementation if not already happened. */
if (__glibc_unlikely (initialized <= 0))
{
if (initialized == -1)
return;
me ();
}
/* If this is not the correct program just use the normal function. */
if (not_me)
{
(*freep) (ptr);
return;
}
/* `free (NULL)' has no effect. */
if (ptr == NULL)
{
catomic_increment (&calls[idx_free]);
return;
}
// rest of the implementation
增量,但这个实现也可能是一个后备实现或其他东西;这不是我第一次阅读一个库函数,它的实际实现是在其他地方完成的,在汇编或其他地方,或者有针对不同架构或其他的专门版本。