假设我有一个结构定义:
Suppose I have a struct definition:
struct thing { thing* x; int z; thing() : x(this), z(0) {} void foo() const { this->x->z++; } };请注意,我创建了一个指向自己的可变指针(邪恶的笑声)
Note that I create a mutable pointer to myself (evil laugh)
然后我以后可以这样使用:
And then I can use this later like this:
int main() { const thing c; c.foo(); assert(c.z == 1); c.foo(); assert(c.z == 2); return c.z; }如您所见,我似乎可以更改一个常数。 ....这是UB吗?
And as you can see it seems that I can change a constant value......is this UB?
推荐答案[dcl.type.cv] p4:
[dcl.type.cv]p4:
除了任何声明为 mutable ([dcl.stc])的类成员可以修改,尝试在生存期内修改([expr.ass],[expr.post.incr], [expr.pre.incr])const对象([basic.type.qualifier])( [basic.life])导致行为不确定。
Except that any class member declared mutable ([dcl.stc]) can be modified, any attempt to modify ([expr.ass], [expr.post.incr], [expr.pre.incr]) a const object ([basic.type.qualifier]) during its lifetime ([basic.life]) results in undefined behavior.
[basic.type.qualifier] p1:
[basic.type.qualifier]p1:
常量对象是类型为 const T 的对象或非可变对象
A const object is an object of type const T or a non-mutable subobject of such an object.
cz 是一个const对象,因为它是 c 的不可变量子对象。您的代码尝试在其生命周期内对其进行修改。因此,该代码具有未定义的行为。
c.z is a const object, because it is a non-mutable subobject of c. Your code attempts to modify it during its lifetime. It follows that the code has undefined behavior.
更多推荐
常数值变更
发布评论