【问题标题】:Using const_cast<> and changing the value at the address does not change original variable [duplicate]使用 const_cast<> 并更改地址处的值不会更改原始变量[重复]
【发布时间】:2015-03-26 17:07:20
【问题描述】:
#include <iostream>

using namespace std;

int main()
{
    const int kiNum = 100;
    int* ptr = const_cast<int*>(&kiNum);
    *ptr = 200; 
    cout<<"kiNum: "<<kiNum; // The value still prints 100 on the console??
    return 0;
}

output:
kiNum = 100 

在上面的代码 sn-p 中,我试图在 const_cast 之后更改 const 整数的值,然后更改地址处的值,但控制台仍然打印旧值(我使用的是 Visual Studio 2012)

【问题讨论】:

标签: c++ c++11


【解决方案1】:

写入定义为 const 的东西是未定义的(当然假设你抛弃了 const)。

http://en.cppreference.com/w/cpp/language/const_cast

这是一个非常准确的网站。如果您对语言功能有疑问,恕我直言,它总是值得查找。

【讨论】:

    猜你喜欢
    • 2018-04-16
    • 2013-11-25
    • 2015-12-30
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2017-07-20
    • 2018-02-09
    • 2011-08-15
    相关资源
    最近更新 更多