【问题标题】:Why can't I change the value of a const data (int in my case) using const_cast [duplicate]为什么我不能使用 const_cast [重复] 更改 const 数据(在我的情况下为 int)的值
【发布时间】:2014-09-16 17:06:05
【问题描述】:

我有一段程序如下图:

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    const int i = 100;
    cout<<"const i::"<<i<<endl;
    const_cast<int&>(i) = 200;
    cout<<"const i after cast::"<<i<<endl;
    return EXIT_SUCCESS;
}

但是i的值还是100。难道const_cast不应该改变i的值吗?

【问题讨论】:

  • 我要在这里冒昧地说一个常数,根据定义,不能更改。它是恒定的。
  • 因为尝试这样做是未定义的行为(但我敢打赌这是重复的)。
  • "const_cast 不应该改变i 的值吗?"不,如果您只有一个常量引用,它允许您更改非常量值;但不应该改变一个常数值。否则它不会是恒定的。

标签: c++ const-cast


【解决方案1】:

根据其定义,常量数据是常量,尝试更改常量数据会导致undefined behavior

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 2022-01-20
    • 2023-03-20
    相关资源
    最近更新 更多