Static const member not defined

Using the standard compiler 03 (safety critical gcc-3.3.2). The standard states that static member objects must be defined (9.4.2 (4)). It also states that the one-definition rule is met, but no diagnostics are required (9.4.2 (5)). Is the following code valid?

struct fred
{
    static const int JOE=1;
    int m_joe;
    fred() : m_joe(JOE) {}
};

      

That is, there is no "static const int fred :: JOE;". I am asking because we have a case (apparently) where the static constant int in the template class was never defined and the code worked in some contexts but not others. I replaced static const int with an enum and it worked in all cases. Were we definitely in the Land of Undefined Behavior?

+3


source to share


1 answer


A static const int

defines a compile-time constant; I'm afraid I cannot refer to a specific part of the standard. The only time you need a definition for it is to try to take its address or create a link. If you use enum instead, the compiler will create a temporary variable for you when you need a reference.



struct test
{
    static const int one = 1;
    enum { two = 2 };
};

void printint(const int & i)
{
    cout << i << endl;
}

int main() {
    printint(test::one);  // error
    printint(test::two);  // no error
    return 0;
}

      

+1


source







All Articles