本文介绍了为什么const_cast没有修改调用方函数中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码段,

#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 ?

推荐答案

,您的程序包含未定义的行为.

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:

const_cast上的第5.2.11/7段包含进一步的警告:

Paragraph 5.2.11/7 on const_cast contains a further warning:

这篇关于为什么const_cast没有修改调用方函数中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:40