C++中静态对象的销毁顺序

2022-01-05 00:00:00 static c++ destruction

我可以控制破坏静态对象的顺序吗?有什么办法可以强制执行我想要的命令吗?例如,以某种方式指定我希望某个对象最后销毁,或者至少在另一个静态对象之后销毁?

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?

推荐答案

静态对象以与构造相反的顺序销毁.而且施工顺序很难控制.唯一可以确定的是,在同一个编译单元中定义的两个对象将按照定义的顺序构造.其他任何东西都或多或少是随机的.

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.

相关文章