The code:
static const void *const uniquePtr = &uniquePtr;
…will provide a unique void
pointer in the compilation unit. It's handy for generating a unique handle or name for APIs that like to take a name as a void*
in this way.
Examples of use:
objc_setAssociatedObject
and objc_getAssociatedObject
addObserver:forKeyPath:options:context:
It'd be sensible to wrap this pattern in a macro to avoid making a mistake with it, and to encapsulate the idea so that it self documents.
But that leads to the question: is there a name for this idiom that can be used to name the macro?:
#define DECLARE_VOID_THING(name) static const void *const name = &name
DECLARE_VOID_THING(aHandle);
DECLARE_VOID_THING(anotherHandle);
Any thoughts?
As was hashed out above there is (very likely) no standard parlance, so you're free to choose whatever you think best. Perhaps something like UNIQUE_VOID_POINTER
or some such.
I would call it a self reference
it is not very different from:
struct self {
struct self *moi;
} me = { &me};
This has the additional advantage that you don't have to dereference a void*
pointer in order to use it. (eg: assert (me.moi == &me);
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With