这是来自 C++11。
During the construction of a
const
object, if the value of the object or any of its subobjects is accessed through a glvalue that is not obtained, directly or indirectly, from the constructor’s this pointer, the value of the object or subobject thus obtained is unspecified. [ Example:struct C; void no_opt(C*); struct C { int c; C() : c(0) { no_opt(this); } }; const C cobj; void no_opt(C* cptr) { int i = cobj.c * 100; // value of cobj.c is unspecified cptr->c = 1; cout << cobj.c * 100 // value of cobj.c is unspecified << ’\n’; }
— end example ]
为什么它只适用于 const
对象?
最佳答案
要真正理解您需要与委员会成员通信的基本原理,或者至少阅读相关讨论。我帮不了你。
这在上下文中的作用是对 const 对象的构造施加比一般应用更严格的限制。通常适用的规则在 S12.7 中有一定篇幅的介绍,并且广泛地关注对象的生命周期。例如,它们不禁止使用别名。
对 const 对象的限制将允许实现者采用更积极的优化策略。例如,一个对象可能在翻译时构建,或者通过将其提升出循环而只构建一次,或者完全优化掉。由于 const 对象不会改变,编译器通常不必担心别名,但(如示例代码所示)在这种特殊情况下他们会担心。
我不禁想到一定有这样一种情况,即这条规则可以防止其他一些外部可见的违反 const 要求的行为。给出的示例不是这种情况,我一直找不到。也许其他贡献者可以提供帮助。
关于c++ - C++ 标准第 12.1.14 段的基本原理是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21643572/