为什么 const_cast 不修改调用函数中的值? [英] Why const_cast is not modifying the value in caller function?
问题描述
对于以下代码段,
#include <iostream>
using namespace std;
void fun(const int *p)
{
int *q = const_cast<int *>(p);
*q = *q * 10;
cout<<"q: "<<q<<" Value: "<<*q<<endl;
}
int main()
{
const int a = 10;
const int *z = &a;
fun(z);
cout<<"z: "<<z<<" "<<"Address of a: "<<&a<<endl;
cout<<"value at z: "<<*z<<" value in a: "<<a<<endl;
}
产生的输出是
q: 0x7fff65910fcc Value: 100
z: 0x7fff65910fcc Address of a: 0x7fff65910fcc
value at z: 100 value in a: 10
为什么我尝试在 fun() 中修改 a 的值却没有修改它?
Why the value of a is not modified even though i tried to modify it in fun()?
为什么a和指针z的地址相同,但值不同?
How come the address of a and the pointer z are same but the values are different?
const_cast 是某种未定义的行为吗?
Is it some kind of undefined behavior with const_cast ?
推荐答案
const_cast 是某种未定义的行为吗?
Is it some kind of undefined behavior with const_cast ?
是的,您的程序包含未定义的行为.
Yes, your program contains undefined behavior.
这意味着你不能对其输出有任何期望.原因由 C++11 标准的第 7.1.6.1/4 段给出:
This means that you cannot have any expectation on its output. The reason is given by paragraph 7.1.6.1/4 of the C++11 Standard:
除了声明mutable
(7.1.1)的任何类成员都可以修改外,任何修改const
的尝试对象在其生命周期 (3.8) 中会导致未定义的行为
Except that any class member declared
mutable
(7.1.1) can be modified, any attempt to modify aconst
object during its lifetime (3.8) results in undefined behavior
const_cast
上的第 5.2.11/7 段包含进一步的警告:
Paragraph 5.2.11/7 on const_cast
contains a further warning:
[ 注意:根据对象的类型,通过指针、左值或指针进行写操作从 const_cast
产生的数据成员丢弃 const
-限定符可能会产生 undefined行为 (7.1.6.1).—尾注 ]
[ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a
const_cast
that casts away aconst
-qualifier may produce undefined behavior (7.1.6.1). —end note ]
这篇关于为什么 const_cast 不修改调用函数中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!