Search code examples
c++staticinitializationstateless

C++ static initialization of stateless class


Suppose I have a class T where

  1. T has no virtual functions.
  2. T instances have no state.
  3. T has static member instances of itself.
  4. T itself has no other state.

Can the C++ static initialization fiasco ruin my program? I don't think so because even if one of the static instances is not initialized before use, that should not matter because T objects are stateless.

I'm interested in doing this for enum-like classes like so:


// Switch.h

class Switch {
public:
    static Switch const ON;
    static Switch const OFF;
    bool operator== (Switch const &s) const;
    bool operator!= (Switch const &s) const;
private:
    Switch () {}
    Switch (Switch const &); // no implementation
    Switch & operator= (Switch const &); // no implementation
};

// Switch.cpp

Switch const Switch::ON;
Switch const Switch::OFF;

bool Switch::operator== (Switch const &s) const {
    return this == &s;
}

bool Switch::operator!= (Switch const &s) const {
    return this != &s;
}

Solution

  • To answer the first part of your question, if T has a constructor which has side effects then you can in fact get burned by static initialization fiasco.