指向常量的指针 [英] Pointer to constant

查看:57
本文介绍了指向常量的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,通过引用将参数(特别是如果它们像结构一样大的话)传递给函数是一种很好的做法.为了应用最小特权"原则,如果该函数不应该更改这些传递变量的值,那么我们需要将它们的引用作为指向常量的指针传递.我的问题是,作为常量的指针传递并不能阻止改变函数内的值(你可以考虑附加的代码),那么我们如何防止这种做法?

It is known that it is a good practice to pass arguments (specially if they are of big size like structures) to functions by reference. And to apply the principle of "least privilege", if that function is not supposed to change the values of these passed variables then we need to pass their references as a pointer to constant. My question is, passing as a pointer to constant can not prevent changing the values within the function (You may consider the attached code), so how can we prevent such practice?

void print(const int *ptr) {
    printf("%d\n", *ptr);
    int * p = ptr;
    *p = 11;
}

我不是在这里讨论我们是否可以通过指针改变常量的值.我知道我们可以.但我的问题是如何防止这种做法来执行最小特权原则?否则,如果我们可以像上面的代码所示轻松地使用它,那么将引用作为指向常量的指针有什么用处

I am not discussing here whether we can change the value of a constant through pointers or not. I know that we can. But my question is how to prevent such practice to enforce the principle of least privilege? otherwise what is the use of passing a reference as a pointer to constant if we can play around it easily as shown in the code above

推荐答案

这段代码 int * p = ptr; 格式错误,不是有效的 C.

This code int * p = ptr; is ill-formed, it is not valid C.

根据简单赋值规则(6.5.16.1),强调我的:

According to the rules of simple assignment (6.5.16.1), emphasis mine:

符合以下条件之一:

/--/

  • 左操作数具有原子的、限定的或非限定的指针类型,并且(考虑左操作数在左值之后的类型转换)两个操作数都是指向限定或不限定的指针兼容类型的版本,和左边指向的类型有右边所指类型的所有限定符;
  • the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;

Qualifiers 表示类型限定符,例如 constvolatile.代码中的左操作数与右操作数的限定符不同,因此不应编译.

Qualifiers means type qualifiers, such as const or volatile. The left operand in your code doesn't have the same qualifiers as the right operand, so it should not compile.

这篇关于指向常量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆