Once I was reading an awesome C++ FAQ (It is really good!!) and read the topic about how to prevent the static initialization order "fiasco". So the author advises to wrap the static variables into functions, thus to prevent the "fiasco" by maintaining the creation order of variables. But this seems to me a rude workaround. So my question is, is there any modern, more pattern oriented way to prevent this "fiasco" but to wrap the "static stuff" into functions???
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
The more usual way of addressing the problem is to avoid statics whenever possible - and even more so between objects that rely on construction order.
Then construct objects in the required order. For example, if we have two objects x and y, and construction of y will fail if x has not been constructed, then construct x first and supply it to the constructor (or another member) of y)
or
(both of the above assume the constructor of
y
requires a reference).If you need to share
x
andy
between functions, simply pass them to functions as arguments.If you must use statics (i.e. you don't want the typing of passing arguments everywhere) make the statics to be pointers, and initialise them once (for example, in
main()
).But, really, it is best to avoid using statics if at all possible.
The modern, more pattern-oriented way is not to use globals in the first place.
There's no other way around it.
It wouldn't be much of a "fiasco", otherwise!
In most cases, you can declare your "global" data in the main function, and use dependency injection to pass it around, where needed. In other words, do not have static state at all.
In practice, you can have situations where static data is needed. If there are no dependencies to other statics, make the static data
const/constexpr
.In case the static variables do depend on each other, just wrap them in static functions:
To summarize:
Most (90%? 99%?) static/global/shared data should be dependency-injected into where it is used, and not created as static at all.
In the rare cases when statics are required for a reason or another and they do not depend on other statics, declare static variables.
In the very rare cases when statics need to be static and they depend on each other, wap them in static methods.
As a rule of thumb, if you have a lot of the second and third cases, you are not doing enough of the first.