c++ - 增加顶级 const 指针时发生了什么?

标签 c++ constants undefined-behavior const-cast

<分区>

当我试图弄清楚顶级constconst_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 指向一个常量 值。尝试修改常量值确实是 undefined behavior .

如果您改为执行 *q++ 并递增指针,那么您就不会修改常量值,这样就可以了。另一方面,它不再指向有效对象,当您在打印它指向的值时取消引用 q 时,您将拥有 UB。

关于c++ - 增加顶级 const 指针时发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49105320/

相关文章:

c++ - C++模板的基本问题

c++ - 打开exe时的cygwin1 dll

c++ - 在 OpenCV 中将 cv::Mat 转换为 Cvmat*

c++ - C++ 中的 volatile 成员函数与常量成员函数

c++ - const 引用函数参数 : Is it possible to disallow temporary objects?

c++ - 如何抑制源文件中特定宏定义的零参数的 GCC 可变参数宏参数警告

visual-studio - 如何根据 "Configuration Manager"创建自己定义的常量?

c++ - 多个 CRTP 基类的对齐

c++ - 何时在空实例上调用成员函数会导致未定义的行为?

c - 修改只读内存会发生什么?