[英]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的值也沒有修改?
a和指針z的地址為何相同但值卻不同?
const_cast是否有某種未定義的行為?
const_cast是否有某種未定義的行為?
是的 ,您的程序包含未定義的行為。
這意味着您不能對它的輸出有任何期望。 原因由C ++ 11標准的7.1.6.1/4給出:
除了可以聲明任何聲明為
mutable
類成員(7.1.1)之外,任何在其生存期(3.8)內修改const
對象的嘗試都會導致未定義的行為
const_cast
上的第5.2.11 / 7段包含另一個警告:
[ 注意 :根據對象的類型,通過
const_cast
丟棄const
-qualifier的指針,左值或指向數據成員的指針的寫操作可能會產生不確定的行為(7.1.6.1)。 — 尾注 ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.