gpt4 book ai didi

c - 为什么在函数声明中传递 const 指针参数无效

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:49 48 4
gpt4 key购买 nike

问题描述

我有一个函数,它接收一个指向 const double 数组的 const 指针,我在 my_func 中使用大小作为边界检查对其进行循环。

.h 中的声明

void my_func(const double * const my_array, size_t size);

.c 中的实现

void my_func(const double * const my_array, size_t size) {
for (size_t idx = 0; idx < size; idx++) {
do_something_with(my_array[idx]);
}
}

我不想在函数内部更改指针,因此使其成为 * const。我不希望它指向的数据被更改,因此 const double

不过,Clang-Tidy 希望我有函数声明 将常量放在指针上,使其成为

void my_func(const double * my_array, size_t size);

Clang-Tidy: Parameter 'my_array' is const-qualified in the function declaration; const-qualification of parameters only has an effect in function definitions

如果我遵循该建议但想保留上面的约束,我的函数声明和定义将不再相同。

问题

1)
假设我的指针参数不是 const (const double * pointer_arg),如果我将函数内部的 pointer_arg 更改为指向另一个 const double,则更改在我的功能之外可见吗?也就是说,在我执行函数的那一行之后, fill pointer_arg 指向哪里?如果它不可见,是否意味着指针是按值复制的?这可能吗?

2)
声明中的const无效的决定背后的原因是什么?

3)
在声明和定义中使用不同的函数签名可能有什么好处?对于我来说,查看我的头文件并不清楚实现是如何工作的,它会在函数内部是 const 吗,不是吗?这让我或代码的合作者感到困惑。

4)
我应该在声明中删除 const 吗?在这种情况下,最佳做法是什么?

最佳答案

1) Suppose my pointer argument is not const (const double * pointer_arg), if I change pointer_arg inside the function to point to another const double, is will the change be visible outside of my function?

不,它不可见。

That is, after the line I executed my function, where fill pointer_arg point to?

和以前一样。

If it is not visible, does that mean the pointer is copied in by value? Is this even possible?

就是这样。

2) What is the reason behind the decision that const in the declaration has no effect?

因为它是按值传递的,所以 const 没有效果(对调用者)。

3) What might be a benefit of having a different function signature in the declaration and definition?

没有。它实际上什至不应该用 C++ 编译。

4) Should I drop the const in the declaration? What are best practices in this case?

是的,您应该删除 const,因为它没有多大帮助。您只是禁止该函数更改其指针副本,这与调用者无关。

关于c - 为什么在函数声明中传递 const 指针参数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55613360/

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