Why does the Visual C++ compiler refuse to compile this code?
I obviously know that the error is:
Error C2864:
Singleton<T>::p:
Only static const integral data members can be initialized within a class
but why? (i.e. is there a technical reason why it is not allowed?)
Is this compiler-specific behavior or is it mandated by the standard?
It seems to be fine at the global scope, so why not at the class scope?
It also seems like not all compilers mind this.
Also, what is the proper way of fixing this?
template<typename T>
struct Singleton
{
static T *p = 0; // Error C2864
static T *getInstance() { /*...*/ return p; }
};
That’s standard behavior. Only static const integral members can be initialized without a proper definition. All other types need to be defined somewhere, and the initialization is written at the point of definition:
Objects must be defined somewhere. If you define them within your class then its defined at a header file, and you get a different object for each compilation unit that includes it. This is relaxed for const integral types and if you don’t define them then the compiler just replaces it with its literal value. Taking the address of such static const integral would still result in a linker error if no definition is provided.