What#39;s the point of const pointers?(const 指针有什么意义?)
问题描述
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 指针有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:const 指针有什么意义?


基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09