c++ - const_cast 不同的行为 : primitive type vs object type

标签 c++

如果我们将变量声明为 const,即使通过非 const 引用,其内容也不得更改。在下面的代码中,我不明白为什么我会根据类型(原始与对象)得到不同的行为:

#include <iostream>

class MyClass 
{

public:   

   int m_value ;
   MyClass(int value): m_value(value) {} ;


}

int main()
{
 const int x = 0 ;
 const_cast<int &>(x)=20 ;
 std::cout << x << std::endl ; //output 0

 const MyClass a(0) ;
 const_cast<MyClass&>(a).m_value= 20 ;
 std::cout << a.m_value << std::endl ; //output 20 

}

最佳答案

你不能抛弃常量变量 x 的常量性,因为变量 x 是一个常量变量。

const_cast 实际上做的是抛弃 const 指针或引用,因为您的成员 m_value 不是 const 成员,您可以使用 const_cast

read more on this link

 int x = 0 ;
 const int& p = x; 
 // p = 20; // error: p is const
 const_cast<int &>(p)=20 ;
 std::cout << p << std::endl ; //output 20

-------------------------------------------

我的类(class) { 公开:
const int m_value = 0; };

int main(){
  const MyClass a;
  const_cast<MyClass&>(a).m_value= 20 ;// undefined behavior
}

关于c++ - const_cast 不同的行为 : primitive type vs object type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54569144/

相关文章:

c++ - 在 C 和 C++ 中将 char 转换为 int

c++ - 使用 llvm::Function::dump(),链接器给出 "undefined reference to ` llvm::Value::dump() const'"

c++ - 如何在 C++ 中对 vector 进行排序和排名(不使用 C++11)

C++ shared_ptr 和 memcpy 错误

使用给定类型和构造函数参数创建和销毁临时对象的 C++ 函数

c++ - 如何最小化加载 vector 的时间?

c++ - 模板类的成员函数不能返回指向成员结构的指针?

c++ - 重载类还是?

C++ 连接字符串导致 "invalid operands of types ‘const char*’ 和 ‘const char"

C++ Vector 奇怪的行为