gpt4 book ai didi

c++ - 将左 const 添加到指针数组

转载 作者:行者123 更新时间:2023-11-28 05:13:57 25 4
gpt4 key购买 nike

我一次处理多个数组。有些功能需要改变数组,其他人只需要阅读。以这些函数为例:

// Only needs to read from the two arrays.
void f(int const *a[2]) { /* ... */ }

// Changes the two arrays.
void g(int *a[2]) { /* ... */ }

我希望我可以用非常量数组来调用它们。添加一个最右边的 const 总是可能的,左边的 const 会改变类型。我仍然认为 const 只会使它更严格并且应该是可以的。

数据结构可能如下所示:

int *a[2] = {new int[10], new int[10]};

调用 g 没有问题,编译干净:

g(a);

但是,当我用 f 尝试同样的操作时,它不起作用:

f(a);

g++:

const_cast.cpp: In function 'int main(int, char**)':
const_cast.cpp:12:8: error: invalid conversion from 'int**' to 'const int**' [-fpermissive]
f(a);
^

clang++ 给出的消息略有不同:

const_cast.cpp:12:5: error: no matching function for call to 'f'
f(a);
^
const_cast.cpp:4:6: note: candidate function not viable: no known conversion from 'int *[2]' to 'const int **' for 1st
argument
void f(int const *a[2]) {}
^

然后我尝试使用 const_cast 来强制进行此转换:

f(const_cast<int const(*)[2]>(a));

那是行不通的,因为它也改变了间接寻址的数量。

const_cast.cpp:22:36: error: invalid const_cast from type 'int**' to type 'const int (*)[2]'
f(const_cast<int const(*)[2]>(a));
^

不过,我不想放宽对f 的要求。应该清楚用户知道这个函数不会改变数组的内容。还代码库中还有其他我不想更改的情况。

使用正确的 const 创建一个新变量确实有效,但是:

int const *const_a[2] = {a[0], a[1]};
f(const_a);

有没有更简单的方法来做到这一点?

最佳答案

int const*int* 是不相关的类型,您不能将指向后者的指针转换为指向前者的指针。

你不能这样做,因为它不安全,但问题不在于函数可能会修改数组,而是它可以用不可修改的数组替换数组。

考虑

int const constants[] = {1,2,3};

void f(int const** a)
{
*a = constants; // OK, *a and &constants[0] are int const*.
}

int main()
{
int* x;
f(&x);
x[0] = 0; // Modifying a const object; undefined behaviour.
}

(请注意,在函数参数中,T x[2] 等同于T x[]T* x。)

关于c++ - 将左 const 添加到指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43027608/

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