[英]What is the rationale for paragraph 12.1.14 of the C++ standard?
This is from C++11. 这是来自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.在构造
const
对象的过程中,如果通过未从构造函数的this指针直接或间接获得的glvalue访问该对象或其子对象的值,则未指定由此获得的对象或子对象的值。 [ 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 ]
— 结束示例 ]
And why does it only apply to const
objects? 为什么只适用于
const
对象?
To truly understand the rationale you would need to correspond with the members of the Committee, or at least read the relevant discussion. 要真正理解其原理,您需要与委员会成员通讯,或者至少阅读相关讨论。 I can't help you with that.
我不能帮你。
The purpose that this serves in context is to place more stringent restrictions on the construction of const objects than apply generally. 在上下文中这样做的目的是对const对象的构造施加比通常适用的更为严格的限制。 The rules that apply generally are covered at some length in S12.7, and broadly they focus on the lifetime of the object.
通常在S12.7中涵盖了一些适用的规则,并且广泛地将重点放在对象的生命周期上。 They do not forbid aliasing, for example.
例如,它们不禁止混叠。
The restrictions on const objects will allow implementers more aggressive optimisation strategies. 对const对象的限制将使实现者可以采用更积极的优化策略。 For example, an object might be constructed at translate time, or constructed only once by hoisting it out of a loop, or optimised away entirely.
例如,一个对象可能是在翻译时构造的,或者是通过将其提升到循环之外而仅构造一次的,或者是完全优化了的。 Since const objects don't change, compilers do not ordinarily have to worry about aliasing but (as shown in the example code) in this particular case they would.
由于const对象不会更改,因此编译器通常不必担心别名,但是在这种特殊情况下,它们会担心(如示例代码所示)。
I can't help thinking there must be a case where this rule prevents some other externally-visible breach of the const requirements. 我不禁要想到,在某些情况下,此规则会阻止某些其他外部可见的违反const要求的行为。 The example given is not such a case, and I've not been able to find one.
给出的示例不是这种情况,我一直找不到。 Perhaps some other contributor can assist.
也许其他贡献者可以提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.