让我们考虑一下这样的应用:
void foo (char* const constPointerToChar) {
// compile-time error: you cannot assign to a variable that is const
constPointerToChar = "foo";
}
int _tmain(int argc, _TCHAR* argv[])
{
char* str = "hello";
foo(str);
printf(str);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我们删除const关键字:
void foo (char* pointerToChar) {
pointerToChar = "foo";
}
int _tmain(int argc, _TCHAR* argv[])
{
char* str = "hello";
foo(str);
printf(str);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是hello.因此,即使允许函数更改指针,它也会更改指针的副本,并且不会更改原始指针.
这是预期的,因为指针是按值传递的.
我明白为什么事情会这样,但我不明白为什么有人需要声明参数为X* const.
当我们声明函数参数时,X* const我们说"好吧,我在我的函数中保证,我不会修改我自己的指针副本." 但是为什么调用者应该关心他从未见过和使用的变量会发生什么?
我是否正确声明函数参数X* const是没用的?
但是为什么调用者应该关心他从未见过和使用的变量会发生什么?
他没有.实际上,您可以将其const从函数的声明中删除,并且仅将其包含在实现中.
我是否正确声明函数参数
X* const是没用的?
不,它与声明任何其他局部变量一样有用const.读取函数的人会知道指针值不应该改变,这可以使逻辑更容易理解; 没有人可以在不应该的时候通过改变它来意外地打破逻辑.