f***t 发帖数: 25 | 1 对于简单类型的const_cast,下面代码:
int const i=2; //现在i值const了
int* k = const_cast(&i); //用引用也行,结果是一样的
*k=3; //借被const cast 的k改i值;成功;
cout<
cout<<*k<
cout<<&i<
cout<
以上是VC6的编译。
把简单类型换成类就不会有这种现象,这是不是VC6的一个bug? |
t****t 发帖数: 6806 | 2 it's undefined to modify a const value, no matter what method you use.
in other words, if a value is declared as const, you can NOT change it. if
you change it, it's undefined (means: wierd things happen).
【在 f***t 的大作中提到】 : 对于简单类型的const_cast,下面代码: : int const i=2; //现在i值const了 : int* k = const_cast(&i); //用引用也行,结果是一样的 : *k=3; //借被const cast 的k改i值;成功; : cout<: cout<<*k<: cout<<&i<: cout<: 以上是VC6的编译。 : 把简单类型换成类就不会有这种现象,这是不是VC6的一个bug?
|
f***t 发帖数: 25 | 3 Thanks,这个解释说的通.
不过,当时c++设计这种cast的动机,不就是为了改const的值吗?
【在 t****t 的大作中提到】 : it's undefined to modify a const value, no matter what method you use. : in other words, if a value is declared as const, you can NOT change it. if : you change it, it's undefined (means: wierd things happen).
|
l*********s 发帖数: 5409 | 4 Not really ; it is explained in Effective C++
【在 f***t 的大作中提到】 : Thanks,这个解释说的通. : 不过,当时c++设计这种cast的动机,不就是为了改const的值吗?
|
t****t 发帖数: 6806 | 5 no, it's designed to change value referenced by const pointer/reference, but
itself not const. const value is never meant to be changed.
【在 f***t 的大作中提到】 : Thanks,这个解释说的通. : 不过,当时c++设计这种cast的动机,不就是为了改const的值吗?
|
A**u 发帖数: 2458 | 6 哇
你的c++功力真是令我太崇拜啦
but
【在 t****t 的大作中提到】 : no, it's designed to change value referenced by const pointer/reference, but : itself not const. const value is never meant to be changed.
|
f***t 发帖数: 25 | 7 i c. 多谢大牛!
but
【在 t****t 的大作中提到】 : no, it's designed to change value referenced by const pointer/reference, but : itself not const. const value is never meant to be changed.
|
t*******c 发帖数: 288 | 8 check out this:
http://en.cppreference.com/w/cpp/language/const_cast
The reference code has the same error as yours. As stated in Note, "Even
though const_cast may remove constness from any pointer or reference, using
the resulting pointer or reference to write to an object that was declared
const invokes undefined behavior." |