看来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/