问题描述
I'm not talking about pointers to const values, but const pointers themselves.
I'm learning C and C++ beyond the very basic stuff and just until today I realized that pointers are passed by value to functions, which makes sense. This means that inside a function I can make the copied pointer point to some other value without affecting the original pointer from the caller.
So what's the point of having a function header that says:
void foo(int* const ptr);
Inside such a function you cannot make ptr point to something else because it's const and you don't want it to be modified, but a function like this:
void foo(int* ptr);
Does the work just as well! because the pointer is copied anyways and the pointer in the caller is not affected even if you modify the copy. So what's the advantage of const?
const
is a tool which you should use in pursuit of a very important C++ concept:
Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.
Even though it doesn't change the functionality, adding const
generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:
void foo(int* ptr)
{
ptr = 0;// oops, I meant *ptr = 0
}
If you use int* const
, this would generate a compiler error because you're changing the value to ptr
. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const
.
这篇关于const 指针有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!