const 指针的意义是什么?

2021-12-13 00:00:00 pointers c constants c++

我不是在谈论指向 const 值的指针,而是在谈论 const 指针本身.

I'm not talking about pointers to const values, but const pointers themselves.

我正在学习 C 和 C++,而不是非常基本的东西,直到今天我才意识到指针是按值传递给函数的,这是有道理的.这意味着在函数内部,我可以使复制的指针指向某个其他值,而不会影响调用者的原始指针.

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);

在这样的函数中,你不能让 ptr 指向其他东西,因为它是 const 并且你不希望它被修改,而是一个像这样的函数:

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);

工作也一样!因为无论如何都会复制指针,并且即使您修改副本,调用者中的指针也不会受到影响.那么 const 的优势是什么?

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 是一个工具,你应该使用它来追求一个非常重要的 C++ 概念:

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.

即使它没有改变功能,当你做你不想做的事情时,添加 const 会产生一个编译器错误.想象一下以下错字:

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
}

如果您使用 int* const,这将产生编译器错误,因为您将值更改为 ptr.通过语法添加限制通常是一件好事.只是不要太过分――你给出的例子是大多数人不会使用 const 的情况.

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.

相关文章