c++ - 为什么类类型的静态和全局变量是危险的?

标签 c++ c++11 global-variables

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Static_and_Global_Variables

Static or global variables of class type are forbidden: they cause hard-to-find bugs due to indeterminate order of construction and destruction.

如果类类型的全局变量不依赖于其他全局变量,例如 std::string strvar("abc"),那么使用它有什么问题/不安全?

向导还说:

...in addition to banning globals of class type, we do not allow static POD variables to be initialized with the result of a function, unless that function (such as getenv(), or getpid()) does not itself depend on any other globals.

出于同样的原因,我认为 strvar 很好:它的构造函数本身不依赖于任何其他全局变量。

另外我想知道C++11对POD的宽松定义是否有这方面的反射(reflect)?

最佳答案

Google 显然是在努力使规则保持简单。因此,虽然在某些情况下可能非常安全,但描述这些异常(exception)情况会很困难。允许这些异常的好处可能不足以保证这种额外的复杂性。

关于c++ - 为什么类类型的静态和全局变量是危险的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12452707/

相关文章:

google-apps-script - 电子表格脚本和脚本库之间的可变范围

c++ - 为什么图像没有出现在 mfc CListView/CListCtrl 的子项上?

c++ - 动态 boost 线程运行存储在具有共享指针的 vector 中的对象的方法

c++ - 覆盖 QML 文件中设置的 ListModel

c++ - 打印直方图 C++

multithreading - C++ 11 中宽松内存模型的底层机制是什么?

c++ - decltype 和成员函数(非指针)类型

c++ - std::unordered_set的迭代顺序

mysql - 是否有打开/关闭 general_log 全局设置的查询?

python - 分包导入或全路径差