你用const能做到什么程度?你只是在必要的时候才把函数变成const,还是从头到尾到处都用它?例如,想象一个简单的变异子,它接受一个布尔参数:

void SetValue(const bool b) { my_val_ = b; }

这个const真的有用吗?就我个人而言,我选择广泛地使用它,包括参数,但在这种情况下,我想知道它是否值得?

我还惊讶地发现,你可以在函数声明中的形参中省略const,但可以在函数定义中包含它,例如:

. h文件

void func(int n, long l);

. cpp文件

void func(const int n, const long l)

这有什么原因吗?这对我来说有点不寻常。


当前回答

只要可以,我就用const。参数的Const意味着它们不应该改变它们的值。这在通过引用传递时尤其有价值。Const for function声明该函数不应更改类成员。

其他回答

使用const时要记住的一点是,从一开始就将对象设为const要比稍后再尝试将它们放入要容易得多。

当你想要某些东西保持不变时,使用const -它是一个附加的提示,描述了你的函数做什么以及期望什么。我见过许多C API可以处理其中的一些,特别是那些接受C -string的API !

我更倾向于省略cpp文件中的const关键字,而不是头,但由于我倾向于剪切+粘贴它们,它们将同时保留在两个地方。我不知道为什么编译器允许这样做,我猜这是编译器的事情。最佳实践肯定是将const关键字放在两个文件中。

我不使用const作为传递值的参数。调用者并不关心你是否修改参数,这是一个实现细节。

真正重要的是,如果方法没有修改其实例,则将其标记为const。这样做,因为否则你可能会得到大量的const_cast<>,或者你可能会发现标记一个方法const需要更改大量的代码,因为它调用了其他应该标记为const的方法。

如果我不需要修改局部变量,我也倾向于将它们标记为const。我相信,通过更容易地识别“移动部分”,可以使代码更容易理解。

If the parameter is passed by value (and is not a reference), usually there is not much difference whether the parameter is declared as const or not (unless it contains a reference member -- not a problem for built-in types). If the parameter is a reference or pointer, it is usually better to protect the referenced/pointed-to memory, not the pointer itself (I think you cannot make the reference itself const, not that it matters much as you cannot change the referee). It seems a good idea to protect everything you can as const. You can omit it without fear of making a mistake if the parameters are just PODs (including built-in types) and there is no chance of them changing further along the road (e.g. in your example the bool parameter).

I didn't know about the .h/.cpp file declaration difference, but it does make some sense. At the machine code level, nothing is "const", so if you declare a function (in the .h) as non-const, the code is the same as if you declare it as const (optimizations aside). However, it helps you to enlist the compiler that you will not change the value of the variable inside the implementation of the function (.ccp). It might come handy in the case when you're inheriting from an interface that allows change, but you don't need to change to parameter to achieve the required functionality.

只要可以,我就用const。参数的Const意味着它们不应该改变它们的值。这在通过引用传递时尤其有价值。Const for function声明该函数不应更改类成员。

有时候(太频繁了!)我必须理清别人的c++代码。我们都知道别人的c++代码几乎从定义上看是一团乱子:)所以我要破译本地数据流的第一件事就是在每个变量定义中放入const,直到编译器开始吠叫。这也意味着const限定值参数,因为它们只是由调用者初始化的花哨局部变量。

啊,我希望变量默认是const的,而非const的变量是可变的:)