为什么全局或静态对象在程序退出时会导致崩溃? [英] Why global or static object can lead to crash when program exit?

查看:154
本文介绍了为什么全局或静态对象在程序退出时会导致崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ Singleton设计模式中, obecalp 提到:


对于许多大型程序,尤其是那些具有动态库的程序。任何非原始的全局或静态对象都可能导致程序在许多平台上退出时出现段错误/崩溃,这是由于库卸载时存在破坏问题的顺序。这是许多编码惯例(包括谷歌)禁止使用非平凡静态和全局对象的原因之一。


详述为什么会发生这种情况?也许一个例子来解释它? 您可能听说过静态初始化顺序失败,其中正在构建的全局引用另一个尚未构建的全局。这个问题的一般解决方案是使用延迟初始化对象(首次使用时初始化)。

那么,同样的失败可能会在销毁时发生,如果析构函数对象引用另一个已经被破坏的对象;不幸的是,这个问题没有银弹解决方案,因为析构函数的代码可以是任意复杂的。



一个解决方案就是禁止使用这种不合适的方式功能。


In C++ Singleton design pattern, obecalp mentioned that:

For many larger programs, especially those with dynamic libraries. Any global or static object that's none primitive can lead to segfaults/crashes upon program exit on many platforms due to order of destruction issues upon libraries unloading. This is one of the reasons many coding conventions (including Google's) ban the use of non-trivial static and global objects.

Can someone elaborate why this can happen? Maybe an example to explain it?

解决方案

You may have heard of the static initialization order fiasco where a global being built references another global that is not yet built. The general solution to this issue is to use lazy initialized objects (initialization on first use).

Well, the same fiasco may occur at destruction time, if the destructor of an object references another object which is already destructed; and unfortunately there is no silver bullet solution to this issue since the code of a destructor can be arbitrarily complex.

One solution is simply to forbid the use of this ill-mannered feature.

这篇关于为什么全局或静态对象在程序退出时会导致崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆