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/