gpt4 book ai didi

c++ - 是否可以在数组上使用 const_cast 来更改元素?

转载 作者:搜寻专家 更新时间:2023-10-31 02:10:22 25 4
gpt4 key购买 nike

这更像是一个学术问题,因为我知道通常要避免 const_cast

但我当时正在做《Thinking in C++》第 3 卷第 27 卷中的练习。 1.

Create a const array of double and a volatile array of double. Index through each array and use const_cast to cast each element to non-const and non-volatile, respectively, and assign a value to each element.

我知道如何const_cast 单个变量:

const int i = 0;
int* j = const_cast<int*>(&i);

*j = 1; // compiles and runs

但无法弄清楚如何让它与数组一起工作。以下编译,但抛出“错误访问”异常,就好像 const 仍然存在一样。

const int sz = 10;
const double cd[sz] {0,1,2,3,4,5,6,7,8,9};
volatile double vd[sz] {0,1,2,3,4,5,6,7,8,9};

double* cdp = const_cast<double*>(cd);
double* vdp = const_cast<double*>(vd);

cdp[0] = 99; // bad access error

我哪里做错了?

最佳答案

请注意:

const int i = 0;
int* j = const_cast<int*>(&i);

*j = 1; // UNDEFINED BEHAVIOR - modify actually const data

不允许通过放弃最初声明为常量的常量来修改对象。编译器可能会将对象(或数组,在您的情况下)的内容放在只读内存中,该内存在机器中比编译器更低的级别强制执行。当你写的时候,它可能会触发一个错误。如果它被声明为 const,您必须永远遵守它,否则在您遇到时会崩溃。

只有如果对象最初被声明为非 const,则在放弃 const 性之后进行修改是可以的。 (也就是说,constness 是后来添加的,可能是作为函数的引用参数。)

为了举例,让我们至少将您的问题改写成一个有效的情况。

// f() takes a reference to an array, but add constness
void f(const double(&arr)[10])
{
// Here it's ok to cast away constness and modify since the
// underlying object isn't declared const (though in general a
// function doesn't know that about its caller, except in
// constrained situations.)
double * array = const_cast<double*>(arr);
array[1] = 99;
}

int main()
{
// NOTE: array is NOT CONST
double arr[10] {0,1,2,3,4,5,6,7,8,9};
f(arr);
}

这很好。

关于c++ - 是否可以在数组上使用 const_cast 来更改元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45395907/

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