我正在与一个声称支持 C++ 的平台的开发人员交谈,但他们同时说,在程序退出时清理的静态变量的数量绑定(bind)到一个魔数(Magic Number)(我认为他们在他们的平台上说是 32),他们说这符合 C++ 标准。
这是正确的吗?
最佳答案
标准规定,如果析构函数有副作用,则必须调用它们。
[basic.start.term]/1:
Destructors (12.4) for initialized objects (that is, objects whose lifetime (3.8) has begun) with static storage duration are called as a result of returning from main and as a result of calling std::exit (18.5). [...]
[basic.stc.static]/2:
If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 12.8. The keyword static can be used to declare a local variable with static storage duration.
但是,在实现限制方面,标准合规性规则确实允许有一些回旋余地:
[intro.compilance]/2.1:
If a program contains no violations of the rules in this International Standard, a conforming implementation shall, within its resource limits, accept and correctly execute that program.
对允许的静态变量数量的硬性限制可能看起来很奇怪,但常见的实现对各种事物都有硬性限制,例如模板实例化深度。
关于c++ - C++中静态变量的个数有限制吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869849/