常数值变更

编程入门 行业动态 更新时间:2024-10-25 06:22:22
本文介绍了常数值变更的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个结构定义:

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.

更多推荐

常数值变更

本文发布于:2023-08-01 08:54:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267024.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!