Suppose I have a class T where
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;
}
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With