c++ - 使用 const_cast 消除常量

标签 c++ const-char

没有。这个问题不重复 When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

此处提出的问题与描述为重复的链接完全不同。

第一个问题: 我在下面的两种情况下使用 const_cast 。其中之一有效。另一个没有。

1. int* const//有效。

在此语法中,变量指向的地址无法更改。所以我使用了 const_cast ,如下所示,它有效:

`
int j=3;
int *k=&j;
int *m=&j;
int* const i=k; 
const_cast<int*>(i)=m; //OK: since i=m would not work so cast is necessary`

2. const int*//不起作用。

所指向的地址可以更改,但值不能更改(尽管可以通过使变量指向不同的地址来更改)。我正在使用的 const_cast 似乎在这里不起作用:

`
int j=9;
int *k=&j;
const int* i1=0;
i1=k; //OK
//*i1=10;//ERROR.`

所以我尝试通过各种方式进行如下类型转换,但没有任何效果:

const_cast<int*>(i1)=10;
const_cast<int*>(*i1)=l;
*i1=const_cast<int>(l);
*i1=const_cast<int*>(10);

第二个问题: 所有的强制转换是否仅可用于指针和引用? 如果图片中没有指针或引用,以下示例是否无效?

const int a=9;
int b=4;
const_cast<int>(a)=b; //cannot convert from 'int' to 'int'. why is compiler
                      //trying to convert from int to int anyways or fails         
                      //when both the types are same.

最佳答案

const_cast应用于表达式,而不是对象,并且它本身也是一个表达式:

§ 5.2.11 [expr.const.cast]/p1:

The result of the expression const_cast<T>(v) is of type T. If T is an lvalue reference to object type, the result is an lvalue; if T is an rvalue reference to object type, the result is an xvalue; otherwise, the result is a prvalue and the lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are performed on the expression v

  1. const_cast<int*>(i)=m;

此调用无效,因为赋值的左侧有一个纯右值值类别和 int*纯右值不支持赋值。正确的语法是 const_cast<int*&>(i)=m; ,但自从 i在您的示例中声明 const ,它将调用未定义的行为

  • const_cast<int*>(*i1)=l;
  • 取消引用 int* 类型的指针创建左值值类别的表达式,并且由于强制转换表达式位于赋值的左侧,因此它应该强制转换为左值引用类型,即 const_cast<int&>(*i1)=10; (前提是 i1 指向的任何内容均未声明 const )。

  • const_cast<int>(a)=b;
  • const_cast<int>(a)部分本身是有效的,特别是您可以将 const_cast 应用于表示既不是指针类型也不是引用类型的对象的表达式。但由于它位于分配的左侧,因此无法编译。即使你将其更改为 const_cast<int&>(a)=b;它将触发未定义的行为,因为 a已声明const


    § 7.1.6.1 [dcl.type.cv]/p4:

    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.

    关于c++ - 使用 const_cast 消除常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32070395/

    相关文章:

    c++ - 为什么 numeric_limits<atomic<X>> 不会编译失败?

    c++ - 从 C++ 中的字符串文字返回 const char*?

    c++ - const char * 在循环期间改变值

    Python 到 C/C++ const char 问题

    C++ streamsize prec = cout.precision(3) - 它是如何工作的?

    c++ - 使用系统调用与基于库的方法来压缩目录的优缺点

    c++ - gRPC WaitForConnected 总是返回 true

    c++ - 运算符 "<<"指向指针

    c++ - 无法将QString转换为Const Char *

    c++ - 使用 unique_ptr 的常量字符指针