When is an integer<->pointer cast actually correct?

后端 未结 15 2655
北荒
北荒 2020-12-13 07:48

The common folklore says that:

  • The type system exists for a reason. Integers and pointers are distinct types, casting between them is a malpractice in the m

15条回答
  •  心在旅途
    2020-12-13 08:51

    The most useful case in my mind is the one that actually has the potential to make programs much more efficient: a number of standard and common library interfaces take a single void * argument which they will pass back to a callback function of some sort. Suppose your callback doesn't need any large amount of data, just a single integer argument.

    If the callback will happen before the function returns, you can simply pass the address of a local (automatic) int variable, and all is well. But the best real-world example for this situation is pthread_create, where the "callback" runs in parallel and you have no guarantee that it will be able to read the argument through the pointer before pthread_create returns. In this situation, you have 3 options:

    1. malloc a single int and have the new thread read and free it.
    2. Pass a pointer to a caller-local struct containing the int and a synchronization object (e.g. a semaphore or a barrier) and have the caller wait on it after calling pthread_create.
    3. Cast the int to void * and pass it by value.

    Option 3 is immensely more efficient than either of the other choices, both of which involve an extra synchronization step (for option 1, the synchronization is in malloc/free, and will almost certainly involve some cost since the allocating and freeing thread are not the same).

提交回复
热议问题