C++ static global non-POD: theory and practice

后端 未结 5 1712
故里飘歌
故里飘歌 2021-02-15 01:49

I was reading the Qt coding conventions docs and came upon the following paragraph:

Anything that has a constructor or needs to run code to be initialized

5条回答
  •  一生所求
    2021-02-15 02:50

    I see no problem with having global objects with constructors.

    They should just not have any dependency on other global objects in their constructor (or destructor).

    But if they do have dependencies then the dependent object must either by in the same compilation unit or be lazily evaluated so you can force it to be evaluated before you use it.

    The code in the constructor should also not be dependent on when (this is related to dependencies but not quite the same) it is executed, But you are safe to assume that it will get constructed at the very least (just before a method is called) and C++ guarantees the destruction order is the reverse of instantiation.

    Its not so difficult to stick to these rules.

提交回复
热议问题