gpt4 book ai didi

c++ - 使用 const_cast 抛弃常量

转载 作者:搜寻专家 更新时间:2023-10-31 00:32:13 26 4
gpt4 key购买 nike

没有。这个问题不重复 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;

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

  1. const_cast<int*>(*i1)=l;

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

  1. 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com