static const
values are treated as r-values just like enum
in 99% of code you'll see. Constant r-values never have memory generated for them. The advantage enum
constants is they can't become l-values in that other 1%. The static const
values are type safe and allow for floats, c-strings, etc.
The compiler will make Foo::Life
an l-value if it has memory associated with it. The usual way to do that is to take its address. e.g. &Foo::Life;
Here is a subtle example where GCC will use the address:
int foo = rand()? Foo::Life: Foo::Everthing;
The compiler generated code uses the addresses of Life
and Everything
. Worse, this only produces a linker error about the missing addresses for Foo::Life
and Foo::Everything
. This behavior is completely standard conforming, though obviously undesirable. There are other compiler specific ways that this can happen, and all standard conforming.
Once you have a conforming c++11 compiler the correct code will be
class Foo {
public:
constexpr size_t Life = 42;
};
This is guaranteed to always be an l-value and it's type-safe, the best of both worlds.