[英]Const-correctness in C pointer-to-pointer parameters
我目前正在开展一个项目,以了解 C 的更高级概念。 我想学习的概念之一是 const-correctness,所以我决定让我的整个代码库都遵守这个想法。
假设我们有这样的 function:
/*
* Creates and displays a window.
*
* Returns non-zero on failure, 0 on success.
*/
extern int window_create(
_In_z_ char const *const pz_title, /* window title */
uint32_t width, /* width in pixels */
uint32_t height, /* height in pixels */
bool isvsync, /* Should VSync be enabled? */
/*
* Pointer to a pointer to a "window" structure
* that will receive the freshly-created window.
* Must not be NULL.
*/
_Outptr_ struct window **pps_window
);
将创建一个 window,然后pps_window
指向的指针将指向新创建的 window 结构。
现在,我是否也应该对window **
参数强制执行 const 正确性? 像这样:
struct window **const pps_window
问题是,在我看来,因为指向指针本身的指针无论如何都是按值传递的,所以不会明确地将其标记为 const 有点毫无意义,因为调用者不必关心指针是否复制堆栈上的内容被修改了,还是添加它仍然是一个好习惯?
我不知道这是否会有所帮助,因为我不太了解您的问题...
C 以 C 的方式做事。 问自己以下代码示例中会发生什么的问题:
#include <stdio.h>
void change_i(int*);
int main() {
const int i = 5;
const int const* pi = &i;
// doesn't compile as expected...
//i = 1;
//*pi = 1;
printf("i is: %d\n", i);
change_i(pi);
printf("i is: %d\n", i);
}
void change_i(int* i) {
*i = 6;
}
我们期待什么 output? 我们会认为 i 仍然是 5 对吗? 虽然 C 并不真正关心......我也喜欢将指针和 const 指针视为数据类型,有些人可能会说我错了,有些人会同意,而 C 发生了什么是我们确实有某种概念数据类型,但由于 C 是弱类型的,所以一切基本上都是相同的类型,是“一堆位”。 在此示例中,C 将 const 指针转换为 function change_i 中的“正常”指针。 结果如下:
i is: 5
i is: 6
这并不意味着 const 没有用,它的作用是说“我无法改变”。 这在编译时确实会产生影响..,一种隐式避免编写像我刚才展示的hacky代码的方法将是低谷,例如:typedefs:
typedef const int const* * const* my_special_integer_type;
my_special_integer_type i = ...;
void do_something(my_special_integer_type i) {
/*
* code...
*/
}
只是提供一个想法,希望这有助于...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.