I’ve read quite a bit about initialization of static class variables in c++ and while the google coding standard says only create statics of plain old data (i.e., primitives & pointers), I see quite a few examples online and in books where the authors violate that guideline.
I’ve also read that as long as you keep the statics in a single compilation unit, that you’re less likely to encounter undefined initialization problems.
ok…so having said that…I want some expert opinions on whether or not I will encounter some problems down the road with code that looks like…
//header file snippet
struct TheStruct {
string theString;
string theString2;
float theFloat;
};
class TheClass {
public:
static const TheStruct Dude;
static const TheStruct Blah;
static const TheStruct TheStructArray[];
TheClass();
virtual ~TheClass();
TheStruct getCurrent();
private:
TheStruct current;
}
//impl file snippet
const TheStruct TheClass::Dude = { "Dude", "Dude", 0 };
const TheStruct TheClass::Blah = { "Blah", "Blah", 0 };
const TheStruct TheClass::TheStructArray[] = {TheClass::Dude, TheClass::Blah};
TheClass::TheClass() : current(TheClass::Dude) {}
TheClass::~TheClass() {}
TheStruct TheClass::getCurrent() {return current;}
I think the getCurrent() method is ok. The static const Dude and Blah are wrapped in a static array TheStructArray that something down the road will use. But, I’m guessing I’m still gonna have the problem with the array if it is used by some other class? For instance, the array may be used by the GUI to present valid options to choose from.
I come from a Java background, so I have frequently used private static final to define some valid “state”…
Thanks!
As long as these three lines are written in that order, there is no problem with your code, as they’re initialized in the order as mentioned, and so you don’t face static initialization order fiasco. Otherwise, you should go through this link to read about what problems you might face, and what solution you must provide.