Benedict Cohen
Benedict Cohen

Reputation: 11920

What is the clearest method for declaring a constant pointer?

I'm using a a pair of functions which use a pointer as a unique key. I want to declare a constant pointer to use as the key. What is the safest and clearest approach to doing this?

Here are 2 possible approaches, but both of which have short comings.

  1. A self referencing pointer:

    static const void * const propertyKey = &propertyKey;
    //...
    objc_getAssociatedObject(object, propertyKey);
    

    Downside: the declaration is long and scary looking! Could easily confuse someone who doesn't know what it's for. Upside: Hard once you understand what it does it's easy to use.

  2. A static const that should be referenced:

    static const char propertyKey;
    //...
    objc_getAssociatedObject(object, &propertyKey);
    

    Downside: When used the variable must be referenced rather than simply used, which is easy to miss (but compiler should point this out as a type mismatch). If the declaration is modified so that a value is assigned then it could have disastrous affects because the uniqueness of the pointer could no longer be guaranteed. Upside: The declaration is easier to grok.

I don't think either of these are immediately obvious. Any better suggestions?

Upvotes: 11

Views: 450

Answers (2)

rra
rra

Reputation: 3887

I also like your first idea. I'd just go with that. Your second idea runs the risk that the compiler may collapse multiple static const char variables into one, since they're guaranteed to always hold the value 0 and, from a compiler's standpoint, I'm not positive they're sufficiently distinct. And I can't think of a better solution than your first idea.

(Lifted to an answer from a discussion in the comments.)

Upvotes: 2

user529758
user529758

Reputation:

3: A pointer that's set to something meaningful yet unique:

static const void *const key = "PropertyKey";

Upvotes: 1

Related Questions