为什么将变量标记为常量?
除了不能更改成本变量之外,它是否使用更少的内存或者可以更快地访问值?
const int a = 1;
int b = 1;
考虑到它是相同的全局、本地和类成员。
谢谢
Possible Duplicate:
Does declaring C++ variables const help or hurt performance?
Besides the point of you can't change cost variables, does it use less memory or can it access the values faster?
const int a = 1;
int b = 1;
Taking into account it's the same global, local and class member.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常两者都不是。它只会使程序更加健壮,因为您(或其他人)无法意外更改该值。
当您想要向消费者表明您不会修改他们的值时,这在公共 API 中尤其有意义。变量的每次修改都意味着程序状态的改变。为了让程序员确保他们的程序正常工作,他们需要跟踪状态,如果他们不知道变量何时或如何更改,这就变得非常困难。
因此,const 的主要目的是语义文档,这是一个非常强大的目的。经常使用
const
。Usually neither. It just makes the program more robust because you (or other people) cannot change the value accidentally.
This makes especially sense in public APIs when you want to show consumers that you won’t modify their values. Every modification of a variable means a change in the program state. In order for programmers to be sure that their program works correctly they need to keep track of the state, and this is tremendously more difficult if they don’t know when or how their variables are changed.
The primary purpose of
const
is therefore documentation of semantics and this is a very powerful purpose. Useconst
often.引用 const 变量并不更快。为此,请使用
restrict
参数。标准库字符串函数将使用 const 让您知道数据结构没有副作用,它用于建立只读策略并避免副作用。
It's not faster to reference a const variable. Use the
restrict
parameter for that.The standard library string functions will use const to let you know there are no side-effects to your data structures, it's used to establish a read-only policy and avoid side-effects.