问题描述
使用 const
可以走多远?你只是在必要时做函数 const
或者你去整个猪,并使用它无处不在?例如,想象一个简单的mutator,它接受一个布尔参数:
How far do you go with const
? Do you just make functions const
when necessary or do you go the whole hog and use it everywhere? For example, imagine a simple mutator that takes a single boolean parameter:
void SetValue(const bool b) { my_val_ = b; }
const
实际上有用吗?
我也很惊讶地发现,你可以省略 const
,但可以将其包含在函数定义中,例如:
I was also surprised to learn that you can omit const
from parameters in a function declaration but can include it in the function definition, e.g.:
.h file
.h file
void func(int n, long l);
.cpp档案
void func(const int n, const long l)
有什么原因吗?
推荐答案
原因是参数的const只应用于函数内部,因为它正在处理数据的副本。这意味着函数签名真的是一样的。
The reason is that const for the parameter only applies locally within the function, since it is working on a copy of the data. This means the function signature is really the same anyways. It's probably bad style to do this a lot though.
我个人倾向于不使用const,除了引用和指针参数。对于复制的对象,它并不重要,虽然它可以更安全,因为它在函数内发出意图。这真的是一个判断电话。我倾向于使用const_iterator虽然当循环的东西,我不打算修改它,所以我想每个他自己,只要const正确的引用类型是严格维护。
I personally tend to not use const except for reference and pointer parameters. For copied objects it doesn't really matter, although it can be safer as it signals intent within the function. It's really a judgement call. I do tend to use const_iterator though when looping on something and I don't intend on modifying it, so I guess to each his own, as long as const correctness for reference types is rigorously maintained.
这篇关于使用'const'函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!