Why const_cast is not modifying the value in calle

2020-02-02 01:57发布

问题:

For below snippet,

#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;
}

the output produced is

q: 0x7fff65910fcc    Value: 100
z: 0x7fff65910fcc   Address of a: 0x7fff65910fcc
value at z: 100      value in a: 10

Why the value of a is not modified even though i tried to modify it in fun()?

How come the address of a and the pointer z are same but the values are different?

Is it some kind of undefined behavior with const_cast ?

回答1:

Is it some kind of undefined behavior with const_cast ?

Yes, your program contains undefined behavior.

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:

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior

Paragraph 5.2.11/7 on const_cast contains a further warning:

[ 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 a const-qualifier may produce undefined behavior (7.1.6.1). —end note ]



标签: c++ linux const