0

Ignoring how repulsive and hacky it is, is the following guaranteed to be safe? If not, why?

//.h
struct foo
{
 const static intptr_t KEY = (intptr_t) "VALUE";
};

//.cpp
void useFoo()
{
 const char * value = (const char *) foo::KEY;
 printf("%s",value);
}
tgoodhart
  • 3,111
  • 26
  • 37
  • Curious, why would you want to do this? – jrok Jun 29 '12 at 19:05
  • As a poor man's way to initialize a const static string in the header. Until c++0x, you could only initialize integral types in the header. You could use #define, or you could initialize the string in the .cpp. I was wondering if this was another way to achieve the same result. – tgoodhart Jun 29 '12 at 19:12

2 Answers2

3

Not only is the code not guaranteed to be safe, the code is ill-formed.

"VALUE" is of type char const[6], which cannot be converted to intptr_t via static_cast.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • I used the wrong type of cast. I was trying to avoid the c-style cast if possible. The spirit of the question is to cast the address of the beginning of a character array literal to an integer in the header then recover it in the .cpp. – tgoodhart Jun 29 '12 at 19:04
2

It is guaranteed not to compile. You cannot use static_cast to convert from pointer to an integral type or viceversa. If it was a reinterpret_cast it would be fragile to say the least as the compiler can do constant folding and the KEY might become non-unique.

Additionally, you should define the static member variable KEY in your application.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489