Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

c++ - Why const_cast is not modifying the value in caller function?

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...