What is the advantage of "static char const * const" over "static const char" for Associated Object keys?

StackOverflow https://stackoverflow.com/questions/21932998

Pregunta

I read on the topic of Associated Objects, which lets you create fake properties for categories.

This article suggests you define the key simply like this:

static const char kNumberKey;

It looks uninitialized but works.

And this article suggests you do something much more complex:

static char const * const ObjectTagKey = "ObjectTag";

Is there an advantage in this longer form? I can see it is initialized. But why const * const? And why does the uninitialized variant above work?

¿Fue útil?

Solución

In the first example, kNumberKey is a single non-modifiable character with a zero value. So it's not usable directly as a key (you would have to take the address of the character, like this : &kNumberKey.

In the second example, ObjectTagKey is a non-modifiable pointer to a string of non-modifiable characters.

What does modifiable mean in this context? If the pointer is modifiable, you can do this in your code :

ObjectTagKey = "my new key";

If the characters are modifiable, you can do this :

ObjectTagKey[3] = 'X';

Having the pointer be non-modifiable helps avoid changing it accidentally, later on in the application's development cycle when development staff has forgotten what ObjectTagKey was used for in the first place. The same logic holds for the characters themselves. So it's safer from a software-maintenance perspective.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top