C ++静态全局非POD:理论与实践 [英] C++ static global non-POD: theory and practice

查看:59
本文介绍了C ++静态全局非POD:理论与实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Qt编码约定文档,并遇到以下段落:

I was reading the Qt coding conventions docs and came upon the following paragraph:

任何具有构造函数或需要运行要初始化的代码的内容都不能用作库代码中的全局对象,因为在运行该构造函数/代码时(在首次使用时,在库加载时,在main(之前),它是未定义的)或完全没有).即使为共享库定义了初始化程序的执行时间,在插件中移动该代码或静态编译库时也会遇到麻烦.

Anything that has a constructor or needs to run code to be initialized cannot be used as global object in library code, since it is undefined when that constructor/code will be run (on first usage, on library load, before main() or not at all). Even if the execution time of the initializer is defined for shared libraries, you’ll get into trouble when moving that code in a plugin or if the library is compiled statically.

我知道理论怎么说,但是我不知道不能理解一点也不"的部分.有时我使用非POD全局const静态变量(例如QString),但我从未想到它们可能未初始化...这是否特定于共享对象/DLL?这仅适用于损坏的编译器吗?

I know what the theory says, but I don't understand the "not at all" part. Sometimes I use non-POD global const statics (e.g: QString) and it never occured to me that they might not be initialized... Is this specific to shared objects / DLLs? Does this happen for broken compilers only?

您如何看待此规则?

推荐答案

根本不"部分只是表示C ++标准对此问题保持沉默.它对共享库一无所知,因此对某些C ++功能与这些功能的交互作用一无所知.

The "not at all" part simply says that the C++ standard is silent about this issue. It doesn't know about shared libraries and thus doesn't says anything about the interaction of certain C++ features with these.

在实践中,我已经看到在GUI,命令行程序,插件和独立应用程序中,在Windows,OSX以及Linux和其他Unices的许多版本上使用的全局非POD静态全局变量.至少有一个项目(使用非POD静态全局变量)具有这些版本所有组合的完整版本.我见过的唯一问题是,一些非常老的GCC版本生成的代码在可执行文件停止时(而不是在卸载库时)在动态库中调用此类对象的dtor.当然,这是致命的(在库已经不存在时调用了库代码),但这已经快十年了.

In practice, I have seen global non-POD static globals used on Windows, OSX, and many versions of Linux and other Unices, both in GUI and command line programs, as plugins and as standalone applications. At least one project (which used non-POD static globals) had versions for the full set of all combinations of these. The only problem I have ever seen was that some very old GCC version generated code that called the dtors of such objects in dynamic libraries when the executable stopped, not when the library was unloaded. Of course, that was fatal (the library code was called when the library was already gone), but that has been almost a decade ago.

但是,当然,这仍然不能保证任何事情.

But of course, this still doesn't guarantee anything.

这篇关于C ++静态全局非POD:理论与实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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