为什么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<<"\t Value: "<<*q<<endl;
}
int main()
{
const int a = 10;
const int *z = &a;
fun(z);
cout<<"z: "<<z<<"\t"<<"Address of a: "<<&a<<endl;
cout<<"value at z: "<<*z<<"\t\t 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
限定符的const_cast
生成的数据成员可能会产生未定义的 行为(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屋!