Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 617
Thomas Eding Avatar asked May 16 '11 22:05

Thomas Eding


2 Answers

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.

like image 116
Mark B Avatar answered Sep 20 '22 23:09

Mark B


I am interested in what are the advantages that you see from, say, an enum wrapped in either a namespace or a class:

namespace Switch {
   enum Switch {
      ON,
      OFF
   };
}

It will be simpler to use in most cases (in your implementation you require users to employ either references or pointers, as the objects are non-copyable), it requires less code (no need to disable the constructors, and create the operators)...

As a matter of fact, in the upcoming standard you almost get that for free without even the use of the namespace:

enum Switch {
   ON,
   OFF
};
// bad, it allows this (as in the current standard):
Switch s = ON;
// good, it does also allow explicit qualification:
Switch s = Switch::ON;
like image 29
David Rodríguez - dribeas Avatar answered Sep 19 '22 23:09

David Rodríguez - dribeas