【发布时间】:2011-05-29 22:50:21
【问题描述】:
我有以下代码:
int main(){
const int a = 1;
const int* b(&a);
int* c = const_cast<int*>(b);
*c = 29;
cout<<*c<<a<<*b;
return EXIT_SUCCESS;
}
为什么'a'的值没有变成29?这是否意味着 const_casting b 时 a 的 const 没有被去掉?
【问题讨论】:
-
另外,为什么编译器会抱怨?我在 gcc 上运行它。
-
查看此答案:stackoverflow.com/questions/357600/is-const-cast-safe/…。特别注意:“如果原始变量实际上是 const,那么使用 const_cast 将导致未定义的行为”。
-
@Daniel,谢谢你的链接。
标签: c++ const-cast