Why would CFRelease(NULL) crash?

前端 未结 4 2108
攒了一身酷
攒了一身酷 2020-12-17 09:31

Is there a reason why CFRelease does not check for NULL? Isn\'t it unacceptable when [nil release]; free(NULL); delete NULL; all work perfectly fine?

4条回答
  •  暖寄归人
    2020-12-17 09:56

    Good point, it doesn't seem to make much sense at first glance. Of course, the behavior is properly documented, but it would be nice if it could handle NULL gracefully. Notice that CFRetain and CFMakeCollectable (new in 10.4, GC enabled in 10.5) exhibit the same behavior. I'm not privy to all the motivations for designing it that way, but the emphasis was probably more on internal consistency with the rest of the CoreFoundation framework.

    It's difficult/impossibly to know why CF was designed that way unless you can ask one of the designers. My best guess is that the designers decided that passing NULL for memory management functions is (should be?) a programming error. One could argue that causing a crash on NULL is a desirable "fail-fast" behavior, since bugs that crash almost immediately are easier to track down than bugs which silently do nothing instead of what you expect. Personally, I prefer the do-nothing-on-null approach, but I guess that's life...

    Given that the API can't/won't change, you can either test for NULL or work around the problem case. One option might be to define an inline function or macro that only calls CFRelease for non-NULL references. In any case, it's probably best to be explicit in your code to avoid confusion down the road.

提交回复
热议问题