对函数参数使用“const"

2022-01-23 00:00:00 constants c++

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 真的有用吗?我个人选择广泛使用它,包括参数,但在这种情况下我想知道它是否值得?

Is that const actually useful? Personally I opt to use it extensively, including parameters, but in this case I wonder if it's worthwhile?

我还惊讶地发现,您可以在函数声明的参数中省略 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 文件

void func(int n, long l);

.cpp 文件

void func(const int n, const long l)

这是有原因的吗?这对我来说似乎有点不寻常.

Is there a reason for this? It seems a little unusual to me.

推荐答案

原因是参数的 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 正确性以供参考types 得到严格维护.

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.

相关文章