c++ - 数组上的 const 值是否与数组上的 const 不同

标签 c++ c arrays

看来const on array会导致用于存储数组的内存在内存中标记为只读。但为什么 const on int 不会做同样的事情呢?

代码在这里:

int main(int argc, const char * argv[])
{

    const int vv = 10 ;
    int * p = (int *)&vv ;
    *p = 5 ; // work well

    const int aa[3] = {11, 12, 13} ;
    int * pp = (int *)&aa[1] ;
    *pp = 100 ; // EXC_BAD_ACCESS

    return 0;
}

最佳答案

第一个和第二个(如第 7.1.6.1/4 节中所述)都会导致未定义的行为:

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

事实上,这是 C++ 风格转换(例如 static_cast)的情况之一,const_cast 除外,would have warned you .

在 C 标准中,§6.7.3/5 中也有相同的引用:

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

关于c++ - 数组上的 const 值是否与数组上的 const 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21156509/

相关文章:

java - 如何为我的 Java 纸牌游戏引用数组中的索引位置

c++ - 返回空字符串文字 VS。返回 nullptr - 它们是否相同?

c++ - 涉及 vector (数组)的快速简单的约束规划

cuda单独编译 "undefined methods"

c - 将两个溢出的整数乘以三分之一

C - 将 char 指针传递给函数的段错误

java - 如何确保映射的总字节数(所有键和值长度的总和)保持在限制范围内?

c++ - 反向代理的典型架构是什么?

c++ - Visual Studio "The debug worker process exited unexpectedly"每次运行都在同一个断点上

C/实时用不同类型的数据初始化内存