Destruction order of static objects in C++ - Stack Overflow
Can I control the order static objects are being destructed? Is there any way to enforce my desired order? For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static object?
我能控制static对象析构的顺序吗?有什么办法按照我希望的顺序执行吗?例如,以某种方式指定我希望的某个对象最后销毁,或至少在另一个静态对象之后销毁?
The static objects are destructed in the reverse order of construction. And the order of construction is very hard to control. The only thing you can be sure of is that two objects defined in the same compilation unit will be constructed in the order of definition. Anything else is more or less random.
静态对象是按照与构造相反的顺序销毁的。而构造的顺序很难控制。您唯一可以确定的是,在同一个编译单元中定义的两个对象将按照定义的顺序构造。其他的都是随机的。
The other answers to this insist that it can’t be done. And they’re right, according to the spec — but there is a trick that will let you do it.
Create only a single static variable, of a class or struct that contains all the other things you would normally make static variables, like so:
对这个问题的其他回答坚持认为这是不可能的。根据标准,他们是对的——但有一个技巧可以让你做到这一点。在类或结构中只创建一个静态变量,该变量包含创建静态变量你通常要做的所有其他内容,如下所示
You can create the variables in whatever order you need to, and more importantly, destroy them in whatever order you need to, in the constructor and destructor for StaticVariables. To make this completely transparent, you can create static references to the variables too, like so:
在StaticVariables的构造函数和析构函数中,可以按照需要的任何顺序创建变量,更重要的是,可以按照需要的任何顺序销毁它们。为了使它完全透明,您也可以创建对变量的静态引用,就像这样
