增加顶级常量指针时发生了什么

What happend when increasing a top-level const pointer?

本文关键字:发生了 什么 指针 常量 增加      更新时间:2023-10-16

当我试图找出顶级常量const_cast时,我编写了一些代码,如下所示。

int main()
{
    // m is a top-level const
    const int m = 10;
    // this is an undefined behavior according to *Primer c++*
    // but I still compile and run this without warning. 
    int *q = const_cast<int *>(&m);
    (*q)++;
    //Then I print the address and the value
    cout<< "the value  of address "<< q <<" is "<< *q <<endl;
    cout<< "the value  of address "<< &m <<" is "<< m <<endl;
    return 0;
}

打印结果让我感到困惑。

the value  of address 0x7ffee6a43ad8 is 11
the value  of address 0x7ffee6a43ad8 is 10

这是未定义的行为之一吗?当我做"(*q(++"时到底发生了什么?

提前致谢

请注意,您的代码执行*q++,它(*q)++

使用*q++,您可以递增指针。有了(*q)++,你就会增加它所指向的内容。

这一切都很好,除了q指向一个常量值。尝试修改常量值实际上是未定义的行为

如果您改为*q++并递增指针,则不会修改常量值,因此可以。另一方面,它不再指向有效对象,当您取消引用q打印它指向的值时,您将拥有 UB。

这是未定义的行为之一吗?

是的。您实际上有两行,每行都可能导致未定义的行为。

int *q = const_cast<int *>(&m);

(*q)++;

在第一个中,您将使用 const_cast 来删除使用 const 限定符创建对象时指针指向的对象的const -ness。

在第二个中,您正在修改const对象的值。

当我做"(*q++("时到底发生了什么?

您必须查看汇编代码才能弄清楚编译器如何处理它。它可以做任何它想做的事。我们不能责怪它做了它所做的事情。