什么是常量指针的地步? [英] What's the point of const pointers?

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

问题描述

我说的不是指针常量的值,但是常量指针自己。

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

做的工作一样好!因为指针反正复制并在调用者的指针,即使你修改副本不会受到影响。那么什么是常量的优势在哪里?

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?

推荐答案

常量是一个工具,你应该追求的是一种非常重要的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.

即使它不改变功能,加入常量生成,当你正在做的事情,你不是故意做了一个编译器错误。想象一下以下错字:

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 。通过语法添加限制是一般一件好事。只是不要把它太远 - 你给的例子是大多数人不使用麻烦的情况下常量

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.

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

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